我有ORM数据类型,如下所示
public class PackData
{
public int PackId
public int ClientId
public DateTime DateCreated
public List<PackItemData> PackItems
}
public class PackItemData
{
public int PackId
public string DeviceId
}
我可以使用Linq查询PackData和PackItemData
var data = DataTable.Where(pack => pack.DateCreated >= startDate
&& pack.DateCreated <= endDate)
我想分组/区分子数据(PackItemData)以获取设备ID的唯一结果
我怎样才能做到这一点?
答案 0 :(得分:0)
我认为您正在寻找SelectMany
。这会使您的List<List<PackItemData>>
变为List<PackItemData>
var data=DataTable.Where(pack => pack.DateCreated >= startDate
&& pack.DateCreated <= endDate)
.SelectMany(i => i.PackItems)
.GroupBy(i => i.DeviceId).Select(i => i.First());
答案 1 :(得分:0)
var groups = DataTable
.Where(pack => pack.DateCreated >= startDate && pack.DateCreated <= endDate)
.SelectMany(pack => pack.PackItems)
.GroupBy(item => item.DeviceId);
您可能希望从SelectMany
开始,这将允许您枚举所有PackDatas中的所有PackItem。这会为您提供IEnumerable<PackItemData>
,然后您可以在分组中使用它。
答案 2 :(得分:0)
Linq GroupBy和不同的方法可以满足您的需求。
var data=DataTable.Where(pack => pack.DateCreated >= startDate && pack.DateCreated <= endDate)
.Select( pack => pack.PackItems)
.GroupBy( p => p.PackId, p => p.DeviceId, (key, p) => new PackItemData { PackId = key, DeviceId = p});
我不是100%这是有效的,因为我还没有进行测试,但这应该让你接近你要去的地方。
答案 3 :(得分:0)
var data = DataTable.Where(pack => pack.DateCreated >= startDate
&& pack.DateCreated <= endDate).SelectMany(s=> s.PackItems).GroupBy(p => p.DeviceId).Select(r=> r);
我认为这应该有用。