LINQ根据类型中的IEnumerable值过滤匿名类型

时间:2009-09-24 20:51:16

标签: c# linq linq-to-sql anonymous-types

我正在使用LINQ to SQL,如:

var b =  
   from s in context.data  
   select new  
   {   
     id = s.id,  
     name = s.name  
     myEnumerable = s.OneToMany
   };

myEnumerable的类型为IEnumberable<T>,我现在想要根据b的各个项的属性获取myEnumerable的子集。例如,假设<T>有属性BerryBerryID,我想做类似的事情:

b = 
   from p in b
   where //p.myEnumerable.myType.BerryID== 13
   select p;

我觉得我错过了一些简单的事情......

3 个答案:

答案 0 :(得分:2)

如果pp.myEnumerable的{​​{1}}中的任何项目等于13,您是否要选择BerryID

b = from p in b
    where p.myEnumerable.Any(t => t.BerryID == 13)
    select p;

或者,您是否希望选择p如果p.myEnumerable中的{em>所有项目BerryID等于13?

b = from p in b
    where p.myEnumerable.All(t => t.BerryID == 13)
    select p;

在选择p.myEnumerable之前,您希望p中的项目满足的条件是什么?

答案 1 :(得分:2)

只保留至少一件项目中BerryID等于13的项目。

 var b = context.data
     .Where(s => s.OneToMany.Any(i => i.BerryID == 13))
     .Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });

仅保留集合中BerryID等于13的所有项目的项目。

 var b = context.data
     .Where(s => s.OneToMany.All(i => i.BerryID == 13))
     .Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });

答案 2 :(得分:2)

由于myEnumerable是一个IEnumerable,你必须在那里做一个。

var filteredData = from p in listOfData
                               where p.InnerData.Where(b=>b.ID == 13).Count() > 0
                               select p;

如果我理解你在说什么......这就是Enumerable中的ID = 13。