c# - Linq 分组和嵌套分组

标签 c# linq aggregate-functions

我正在创建一个可以通过各种分组显示的TreeView。基本类如下:

public class MachineStatus 
{
  public string MachineName {get;set;} 
  public string Department {get;set;}
  public string LocationName {get;set;}
  public IEnumerable<DeviceStatus> Devices {get;set;}
}

public class DeviceStatus
{
  public string DeviceName {get;set;}
  public string DeviceType {get;set;}
  public string IpAddress {get;set;}
  public ConnectionStatus Status {get;set;}
}

这些组将按部门位置设备类型划分。前两个对于 Linq 来说很容易。但是,DeviceType 具有挑战性,因为每个 Machine 可能包含多个不同类型的 Device 对象。

原始数据

Machine 1
  |__ Device A (Type Foo)
  |__ Device B (Type Bar)
Machine 2
  |__ Device C (Type Foo)
  |__ Device D (Type Zed)

结果

Type Bar
  |__ Machine 1
      |__Device B
Type Foo
  |__Machine 1
      |__Device A
  |__Machine 2
      |__Device C
Type Zed
  |__Machine 2
      |__Device D

我想在尝试分组之前我必须展平 MachineStatus 记录列表,但我在使用 SelectMany 时遇到了困惑...

最佳答案

您可以使用 SelectMany 来实现此目的& GroupBy像这样:-

var result = machines.SelectMany(x => x.Devices, 
                                    (machineObj, devices) => new { machineObj, devices })
                     .GroupBy(x => new { x.devices.DeviceType, x.machineObj.Department, 
                                                             x.machineObj.LocationName })
                     .Select(x => new
                                 {
                                     DeviceType = x.Key.DeviceType,
                                     Department = x.Key.Department,
                                     Location = x.Key.LocationName,
                                     machines = x
                                 });

这是完整的Working Fiddle带有我使用过的示例数据,以下是相同的输出。

enter image description here

关于c# - Linq 分组和嵌套分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997814/

相关文章:

c# - 无法转换类型 'AnonymousType#1'

LINQ 生成不正确的 SQL

mysql - 如果没有指定聚合函数,MySQL 会做什么?

javascript - 数据表: click on button does not open view

c# - 人们在使用 Rhino Mocks 的 ASP.NET MVC 中将哪些资源用于 TDD?

c# - linq选择日期之间的位置

asp.net - 如何使用linq仅从日期时间列中获取日期

sql - 6 个月或更长时间的负账款,无论交易如何

mongodb - 从数组聚合中删除元素

c# - 当使用可执行文件的完整路径,以管理员身份运行时,Windows 10 无法访问指定的设备、路径或文件