2013-07-04 25 views
-1

我试图在对象列表中查找原始类型的代码,并将结果获取到新列表中。从列表中获取结果<T> C#

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

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

你已经拥有了(where),只需用'=='而不是'=' – Sayse

回答

4
int associationCode = 1; 

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

值得一提的是,你应该只调用ToList()如果你需要的结果的时候了。

如果您不需要立即得到结果,这会更好。

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

然后,您可以进一步筛选而不会触击数据库。

+0

Ok PeteGO。我看到你的修改有点晚了。但你能告诉我有什么区别 fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode); vs fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList(); 谢谢你的回答! –

+0

那么,你有名单开始(一切都加载),实际上我没有太多的区别,我知道。最主要的是尝试只加载你需要的东西,当你需要时,使用IQueryable和LINQ将为你做到这一点。当您调用.ToList()时,它会提取项目。 – PeteGO

+0

谢谢你的回答。我在这里找到了更多关于它的信息。 http://stackoverflow.com/questions/1938204/linq-where-vs-findall –

0

这应做到:

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

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

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

但现在我看到你的答案PeteGO和我测试和它的作品也,但最后你新添加此.ToList()

现在我感到有点困惑。这两者之间有什么不同?

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

'Where'建立查询并允许你添加额外的限制和动作,比如'GroupBy'和' OrderBy'。通过调用'.ToList()',您正在询问已经完成构建查询的上下文,并且您想要将数据检索到内存中。 – NinjaNye

+0

谢谢!我也在互联网上找到这些补充信息。 http://stackoverflow.com/questions/1938204/linq-where-vs-findall –