如何使用linq(包含一个布尔值和一个子列表)合并行?

时间:2019-05-08 14:28:11

标签: linq

如何合并包含布尔值和子列表的行,如下所示enter image description here

输入为:

PermissionName:14 isAllDepartments:是的, 部门:[{1,false}]

PermissionName:15 isAllDepartments:是的, 部门:[{1,false}]

PermissionName:14 isAllDepartments:False, 部门:[{2,false}]

PermissionName:15 isAllDepartments:False, 部门:[{2,false}]

我期望的输出是:

PermissionName:14 IsAllDepartments:错误 部门:[{1,false},{2,false}]

PermissionName:15 IsAllDepartments:错误 部门:[{1,false},{2,false}]

1 个答案:

答案 0 :(得分:0)

我制作了一个名为myObject的测试类,并将其定义为:

public class myObject
{
   public int PermissionName { get; set; }
   public bool isAllDepartments { get; set; }
   public List<KeyValuePair<int, bool>> Departments {get;set;}
}    

然后我将您的样本数据添加到测试列表:

var list = new List<myObject>();
list.Add(new myObject() { PermissionName = 14, isAllDepartments = true, Departments = new List<KeyValuePair<int, bool>>() { new KeyValuePair<int, bool>(1, false) } });
list.Add(new myObject() { PermissionName = 15, isAllDepartments = true, Departments = new List<KeyValuePair<int, bool>>() { new KeyValuePair<int, bool>(1, false) } });
list.Add(new myObject() { PermissionName = 14, isAllDepartments = false, Departments = new List<KeyValuePair<int, bool>>() { new KeyValuePair<int, bool>(2, false) } });
list.Add(new myObject() { PermissionName = 15, isAllDepartments = false, Departments = new List<KeyValuePair<int, bool>>() { new KeyValuePair<int, bool>(2, false) } });

然后我按PermissionName将列表项分组在一起,并进行选择以合并其他两个属性:

var grouped = list.GroupBy(x => new { x.PermissionName })
                    .Select(o => new myObject()
                    {
                        PermissionName = o.Key.PermissionName,
                        isAllDepartments = o.Select(i => i.isAllDepartments == false) != null ? false : true,
                        Departments = o.SelectMany(d => d.Departments).Distinct().ToList()
                    })
                    .ToList();

o.Select(i => i.isAllDepartments == false) != null ? false : true将选择组中isAllDepartments设置为false的任何项目。如果不为null,则至少找到一项,因此将其设置为false,否则为true(根据评论)。

Departments = o.SelectMany(d => d.Departments).Distinct().ToList()将部门列表合并在一起,并且仅采用不同的int,bool对。