从列表中获取结果<;T>;C#

本文关键字:gt 列表 lt 获取 结果 | 更新日期: 2023-09-27 18:20:58

我试图在对象列表中找到一个基元类型的代码,并将结果放入一个新列表中。

我一直在谷歌上寻找类似的东西,但每个人都在谈论列表之间的交集,我想要这样的东西。

            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);

从列表中获取结果<;T>;C#

int associationCode = 1;
List<Entity> newList = list.Where(e => e.AssociationCode == associationCode).ToList();

值得一提的是,只有当您需要立即得到结果时,才应致电ToList()

如果你不需要马上得到结果,这会更好。

IQueryable<Entity> entities = list.Where(e => e.AssociationCode == associationCode);

然后,您可以在不影响数据库的情况下进行进一步筛选。

这应该做到:

var newList = list.Where(e => e.AssociationCode == AssocCode).ToList()

我在一分钟前解决了我的问题。这是这样的。

            List<Entity> newList =list.FindAll(item => item.AssociationCode == associationCode)

但现在我看到了你的答案,PeterGO和我测试了一下,它也有效,但最后你新添加了这个。ToList()

现在我有点困惑。这两个有什么不同。

            fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode);
            vs
            fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList();