如何将C#列表记录与同一列表中的记录合并

时间:2013-08-29 18:47:20

标签: c# linq list merge

我有以下linq

var unionOperations =
      (from r in gropOperations
       select new
          {
            r.OPERATIONID,
            r.OPERATIONNAME,
            r.ISACTIVE
          })
       .Union(from m in customOperations
              select new
                {
                    m.OPERATIONID,
                    m.OPERATIONNAME,
                    m.ISACTIVE
                }
              );

它返回对象列表,如下所示,

{ OPERATIONID = 1050, OPERATIONNAME = "NEW", ISACTIVE = TRUE }
{ OPERATIONID = 1050, OPERATIONNAME = "NEW", ISACTIVE = FALSE }
{ OPERATIONID = 1051, OPERATIONNAME = "EDIT", ISACTIVE = TRUE  }
{ OPERATIONID = 1052, OPERATIONNAME = "DELETE", ISACTIVE = TRUE  }
{ OPERATIONID = 1053, OPERATIONNAME = "PRINT", ISACTIVE = TRUE  }

现在我想要一个如下列表:

{ OPERATIONID = 1050, OPERATIONNAME = "NEW", TRUE  } 
{ OPERATIONID = 1051, OPERATIONNAME = "EDIT", TRUE }
{ OPERATIONID = 1052, OPERATIONNAME = "DELETE", TRUE }
{ OPERATIONID = 1053, OPERATIONNAME = "PRINT", TRUE }

真正发生的是它将前两个记录(OPERATIONID = 1050)与ISACTIVE值的“或”操作合并;

1 个答案:

答案 0 :(得分:3)

var result = unionOperations.GroupBy(x => x.OPERATIONID)
                .Select(g => {
                    var item = g.First();
                    return new {
                        OPERATIONID = item.OPERATIONID,
                        OPERATIONNAME =item.OPERATIONNAME,
                        ISACTIVE = g.Aggregate(false, (r, x) => r |= x.ISACTIVE)
                    };
                })
                .ToList();