使用group by帮助LINQ查询

时间:2010-10-05 12:04:43

标签: c# linq-to-objects

我有以下列表:

1: true; 
2: false;    
2: true;   
3: false;   
3: false;  
3: false;

我想要一个LINQ查询来获取如下集合:

键,分组项之间的OR运算,例如:

2: false | true  = true

结果必须是:

1: true   
2: true   
3: false

提前致谢

1 个答案:

答案 0 :(得分:3)

// my sample data
var list = new[] {
    new {key = 1, value = true},
    new {key = 2, value = false},
    new {key = 2, value = true},
    new {key = 3, value = false},
    new {key = 3, value = false},
    new {key = 3, value = false},
};
// the actual code
var groups = from pair in list
          group pair by pair.key into grp
          orderby grp.Key
          select new {
              grp.Key,
              Value = grp.Aggregate(false, (x, y) => x || y.value)
          };
// display the result
foreach (var grp in groups)
{
    Console.WriteLine("{0}: {1}", grp.Key, grp.Value);
}

请注意,您也可以使用Any进行聚合,其优点是可以更快地进行短路:

      select new { grp.Key, Value = grp.Any(y => y.value) };