[英]Getting results from a List<T> C#
I trying to find a code of primitive type inside a List of objects and get the results into a new list. 我试图在对象列表中查找原始类型的代码,并将结果放入新列表中。
I've been looking for something like that in Google but everyone talks about intersection between Lists and I want something like this. 我一直在Google中寻找类似的东西,但是每个人都在谈论List之间的交集,我想要这样的东西。
int AssocCode = 2;
//Entity.ID
//Entity.Name
//Entity.AssociationCode
List<Entity> list = new List<Entity>();
list.Add(new Entity(1, "A", 1));
list.Add(new Entity(2, "B", 2));
list.Add(new Entity(3, "C", 3));
list.Add(new Entity(4, "D", 2));
list.Add(new Entity(5, "E", 2));
/*I want the results for finding that code inside the collection**/
List<Entity> newList = list .... find/intersect/select/remove/whatever (x => x.AssociationCode = AssocCode);
int associationCode = 1;
List<Entity> newList = list.Where(e => e.AssociationCode == associationCode).ToList();
Worth mentioning that you should only call ToList()
if you need the results right away. 值得一提的是,仅当您需要结果时才应调用
ToList()
。
This is better if you don't need the results right away. 如果您不需要立即获得结果,这会更好。
IQueryable<Entity> entities = list.Where(e => e.AssociationCode == associationCode);
You can then filter further without hitting the database. 然后,您可以进一步过滤而无需访问数据库。
应该这样做:
var newList = list.Where(e => e.AssociationCode == AssocCode).ToList()
I solved it 1 minute ago my question. 1分钟前我解决了我的问题。 That works like this.
就是这样。
List<Entity> newList =list.FindAll(item => item.AssociationCode == associationCode)
But now I see your answer PeteGO and I tested and it works also but at the end you new to add this .ToList() 但是现在我看到了您的答案PeteGO,并且进行了测试,它也可以工作,但最后您是新添加此.ToList()的人
Now I am a little bit confused. 现在我有点困惑。 What is the different between these 2.
这两个有什么区别
fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode);
vs
fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.