我在编写LINQ查询时需要一些帮助,我试图在其中进行一些“条件/复合”分组。 (不确定这是正确的术语)。让我解释。
如果我有以下类(class):
class Device
{
int Id;
string DeviceType;
string DeeviceValue;
}
class Employee
{
int Id;
int SupervisorId;
int CountryId;
List<Device> Devices = new List<Device>();
}
从这可以说我有这些对象:
List<Employee> Employees = new List<Employee>();
var emp1 = new Employee();
emp1.Id = 1;
emp1.CountryId = 1;
emp1.SupervisorId = 1;
Device dev1 = new Device();
dev1.Id = 1;
dev1.DeviceType = "Desk Phone";
dev1.DeviceValue = "132456789";
emp1.Devices.Add(dev1);
Employees.Add(emp1);
var emp2 = new Employee();
emp2.Id = 2;
emp2.CountryId = 1;
emp2.SupervisorId = 1;
Device dev2 = new Device();
dev2.Id = 2;
dev2.DeviceType = "Desk Phone";
dev2.DeviceValue = "123456789";
emp2.Devices.Add(dev2);
Device dev6 = new Device();
dev6.Id = 6;
dev6.DeviceType = "Conference Phone";
dev6.DeviceValue = "123456789";
emp2.Devices.Add(dev6);
Employees.Add(emp2);
var emp3 = new Employee();
emp3.Id = 3;
emp3.CountryId = 2;
emp3.SupervisorId = 1;
Device dev3 = new Device();
dev3.Id = 3;
dev3.DeviceType = "Desk Phone";
dev3.DeviceValue = "456789123";
emp3.Devices.Add(dev3);
Employees.Add(emp3);
var emp4 = new Employee();
emp4.Id = 4;
emp4.CountryId = 2;
emp4.SupervisorId = 4;
Device dev4 = new Device();
dev4.Id = 4;
dev4.DeviceType = "Desk Phone";
dev4.DeviceValue = "987123456";
emp4.Devices.Add(dev4);
Device dev5 = new Device();
dev5.Id = 5;
dev5.DeviceType = "Dealerboard";
dev5.DeviceValue = "987123456";
emp4.Devices.Add(dev5);
Employees.Add(emp4);
由此,我想创建一个按-> SupervisorId-> CountryId-> DeviceType分组的查询。很好,我在下面的查询中得到了我想要的东西。
var result = Employees.SelectMany(e => e.Devices, (employee, devices) => new { employee, devices })
.GroupBy(e => new { e.devices.DeviceType, e.employee.SupervisorId, e.employee.CountryId })
.Select(e => new
{
DeviceType = e.Key.DeviceType,
Supervisor = e.Key.SupervisorId,
Country = e.Key.CountryId,
employees = e
});
我遇到的问题是,我想创建一个DeviceType组,该组可以包括“Desk Phone”和“Conference Phone”多种设备类型,而不是为每种设备类型都拥有一个单独的组。
编辑-为了完整性
上面的查询给了我以下结果
我追求的结果是:
有没有一种方法可以通过LINQ并修改我已经拥有的查询?
任何帮助将非常感激。
皮特
最佳答案
创建具有每个设备类型的键和其组的值的字典,然后在分组时使用字典
var deviceGroup = new Dictionary<string, string>() { { "Desk Phone", "Phone" }, { "Conference Phone", "Phone" } };
var result = Employees.SelectMany(e => e.Devices, (employee, devices) => new { employee, devices })
.GroupBy(e => new {
DeviceGroup = deviceGroup.ContainsKey(e.devices.DeviceType) ?
deviceGroup[e.devices.DeviceType]
: e.devices.DeviceType,
e.employee.SupervisorId, e.employee.CountryId })
.Select(e => new
{
DeviceGroup = e.Key.DeviceGroup,
Supervisor = e.Key.SupervisorId,
Country = e.Key.CountryId,
employees = e
});
关于C#Linq嵌套 "conditional/composite"分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32604055/