0

假设我有 2 个列表看起来像

      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     

基本上我需要比较和合并这两个列表,如果某个标志在 B 中设置为 true,我应该选择它而不是 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      
4

2 回答 2

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)
        });
于 2012-08-28T14:05:39.097 回答
1

不确定它是否会比 concat/groupby 更快/更慢,但从技术上讲,您正在执行的操作是 a 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,
    });
于 2012-08-28T14:23:19.960 回答