You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用LINQ按Zone分组DeviceModel集合,得到指定分组结果?

按ZoneName分组设备的正确LINQ实现

你的原代码核心问题是直接按整个Zones列表分组,而非单个区域的ZoneName,而且一个设备可能关联多个区域,需要先将设备与每个对应的区域名做关联(扁平化),再进行分组。

类定义回顾

public class DeviceModel
{
    public List<ZoneModel> Zones { get; set; }
    public string Serial { get; set; }
}

public class ZoneModel
{
    public string ZoneName { get; set; }
}

正确实现方式

方式一:LINQ查询表达式

List<DeviceModel> deviceList = new List<DeviceModel>();
// 填充设备数据逻辑...

IEnumerable<IGrouping<string, DeviceModel>> deviceByZoneGroups =
    from device in deviceList
    where device.Zones != null && device.Zones.Any()
    from zone in device.Zones
    group device by zone.ZoneName into zoneGroup
    orderby zoneGroup.Key
    select zoneGroup;

方式二:LINQ方法链写法

IEnumerable<IGrouping<string, DeviceModel>> deviceByZoneGroups = deviceList
    .Where(device => device.Zones != null && device.Zones.Any())
    .SelectMany(device => device.Zones.Select(zone => new { device, zone.ZoneName }))
    .GroupBy(item => item.ZoneName, item => item.device)
    .OrderBy(group => group.Key);

逻辑说明

  1. 过滤无效数据:先用Where排除没有区域(Zones为null或空列表)的设备
  2. 扁平化关联:通过SelectMany(或查询表达式中的嵌套from)将每个设备拆分为多个“设备+区域名”的组合,让一个关联多区域的设备对应到每个区域条目
  3. 分组与排序:按ZoneName进行分组,分组元素为对应的DeviceModel,最后按区域名排序得到结果

内容的提问来源于stack exchange,提问作者Adrien Ruffie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:25:53