如何用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);
逻辑说明
- 过滤无效数据:先用
Where排除没有区域(Zones为null或空列表)的设备 - 扁平化关联:通过
SelectMany(或查询表达式中的嵌套from)将每个设备拆分为多个“设备+区域名”的组合,让一个关联多区域的设备对应到每个区域条目 - 分组与排序:按
ZoneName进行分组,分组元素为对应的DeviceModel,最后按区域名排序得到结果
内容的提问来源于stack exchange,提问作者Adrien Ruffie
相关产品推荐
相关产品推荐

