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

本文关键字:列表 记录 合并 | 更新日期: 2023-09-27 18:29:43

我有以下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值的"或"运算合并;

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

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();