gpt4 book ai didi

c# - 使用 Linq 展平设备和仪表数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:57 25 4
gpt4 key购买 nike

我正在使用一个树形控件,它要求我在将数据交给控件之前展平数据。我已经尝试了各种在线示例,但无法完全正确地“展平”数据。

  • 设备有很多米
  • 结果列表必须是 DeviceHierarchyDataItem 的(扁平化)列表

代码看起来像:
我猜我在这里走错了路......

public IQueryable<DeviceHierarchyDataItem> Query(int circuitConnectId)
{
var devices = (from device in UnitOfWork.Device
join deviceCircuit in UnitOfWork.DeviceCircuit on device.Id equals deviceCircuit.DeviceId
where
deviceCircuit.CircuitConnectId == circuitConnectId
select device)
.Include( x=> x.Meters);

// Not sure what to do NEXT (previous attempts have failed)
}

类(class):

public class DeviceHierarchyDataItem
{
public int Id { get; set; } //<-- the 'Id' of the Device or Meter

public int? ChildOf { get; set; } //<-- the 'Id' of the PARENT Device or NULL

public int CircuitConnectId { get; set; }

public string DisplayName { get; set; } //<-- the 'Name' of the Device or Meter
}

public class Device
{
public int Id { get; set; }

public string DeviceName { get; set; }

public List<Meter> Meters { get; set; }
}

public class Meter
{
public int Id { get; set; }

public string MeterName { get; set; }
}

最佳答案

您可以使用 SelectMany展平集合的集合。

var devices = (from device in UnitOfWork.Device
join deviceCircuit in UnitOfWork.DeviceCircuit on device.Id equals deviceCircuit.DeviceId
where
deviceCircuit.CircuitConnectId == circuitConnectId
select device)
.Include( x=> x.Meters);

var deviceHierarchyDataItems = devices
.SelectMany(device => device.Meters.Select(meter => new DeviceHierarchyDataItem
{
Id = meter.Id,
ChildOf = device.Id,
CircuitConnectId = 0, // don't know what you need here
DisplayName = meter.MeterName
}))
.Concat(devices.Select(device => new DeviceHierarchyDataItem
{
Id = device.Id,
ChildOf = null,
CircuitConnectId = 0, // don't know what you need here
DisplayName = device.DeviceName
}));

或者:

var deviceHierarchyDataItems = devices
.SelectMany(device => device.Meters.Select(meter => new DeviceHierarchyDataItem
{
Id = meter.Id,
ChildOf = device.Id,
CircuitConnectId = 0, // don't know what you need here
DisplayName = meter.MeterName
}).Concat(new List<DeviceHierarchyDataItem>()
{
new DeviceHierarchyDataItem
{
Id = device.Id,
ChildOf = null,
CircuitConnectId = 0, // don't know what you need here
DisplayName = device.DeviceName
}
}));

关于c# - 使用 Linq 展平设备和仪表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com