始终在LINQ语句组中选择true / higher值(多列)

时间:2012-08-28 13:59:01

标签: c# linq lambda grouping

假设我有两个类似

的列表
      ID | IsChipCollected | IsShirtCollected | IsPackCollected
A     0                 1                  0                 1
      1                 0                  1                 0
      2                 0                  0                 1      


B     0                 0                  1                 0
      1                 0                  0                 1
      2                 1                  1                 1     

基本上我需要比较和合并2个列表,如果某个标志在B中设置为真,我应该选择它而不是A

我知道如何通过一个专栏实现这一目标,但我正在努力绕着我的脑袋在2列以上的场景中做到这一点

  var result = A.Concat(B)
        .GroupBy(x => x.Id)
        .Select(g => g.OrderByDescending(x => x.IsShirtCollected).First())

如果我在此方面取得任何进展,我会更新我的代码示例,(因为我目前仍在攻击:P)

预期结果

     ID | IsChipCollected | IsShirtCollected | IsPackCollected
      0                 1                  1                 1
      1                 0                  1                 1
      2                 1                  1                 1      

2 个答案:

答案 0 :(得分:4)

var result = A.Concat(B)
        .GroupBy(x => x.Id)
        .Select(g => new {//or new <A and B's generic type>, then change the underCode with proper case
             id = g.Key,
             isShipCollected = g.Max(m => m.IsChipCollected),
             isShirtCollected = g.Max(m => m.IsShirtCollected),
             isPackCollected = g.Max(m => m.IsPackCollected)
    });

修改

遵循Servy(好)的想法(将1/0更改为布尔值)

var result = A.Concat(B)
       .GroupBy(x => x.Id)
       .Select(g => new { 
            id = g.Key,
            isShipCollected = g.Any(m => m.IsChipCollected == 1),
            isShirtCollected = g.Any(m => m.IsShirtCollected == 1),
            isPackCollected = g.Any(m => m.IsPackCollected == 1)
        });

答案 1 :(得分:1)

不确定它是否比concat / groupby更快/更慢,但从技术上讲,您正在执行的操作是Join,因此在实际执行该连接的可读性方面更有意义。

var query = listA.Join(listB, item => item.ID, item => item.ID,
    (a, b) => new
    {
        ID = a.ID,
        IsChipCollected = a.IsChipCollected | b.IsChipCollected,
        IsShirtCollected = a.IsShirtCollected | b.IsShirtCollected,
        IsPackCollected = a.IsPackCollected | b.IsPackCollected,
    });