【问题标题】:LINQ Filter anonymous type based on IEnumerable values within typeLINQ 根据类型内的 IEnumerable 值过滤匿名类型
【发布时间】:2009-09-24 20:51:16
【问题描述】:

我正在使用 LINQ to SQL,例如:

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

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

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

我觉得我错过了一些简单的东西......

【问题讨论】:

  • 你能澄清你的问题吗?您想通过集合 myEnumerable 再次过滤集合 b?您要检查什么条件? myEnumerable 包含 BerryID == 13 的项目?所有项目都必须有 BerryID == 13?

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


【解决方案1】:

由于 myEnumerable 是一个 IEnumerable,因此您必须对其进行 where 操作。

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

如果我明白你在说什么......这是如果 Enumerable 中有一个 ID = 13。

【讨论】:

  • 您可以将 Where(condition).Count() 缩短为 Count(condition)。此外 Any(condition) 比 Count(condition) > 0 更快,因为 Any() 可以在第一次正匹配后停止,而 Count() 必须始终处理完整的序列。
【解决方案2】:

如果p.myEnumerable 中的任何项目的BerryID 等于13,您是否要选择p

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

或者如果p.myEnumerable 中的所有 项的BerryID 等于13,您是否要选择p

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

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

【讨论】:

  • Any/All..cleaner 看起来比我的好。
【解决方案3】:

仅保留集合中至少一项 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 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多