[英]LINQ Create a nested List
我正在尝试将平面列表转换为嵌套列表。
这是我的平面清单:
public class DefectLocationCount {
public string LocationName { get; set; }
public string DefectName { get; set; }
public int TotalCount { get; set; }
}
这是我的嵌套列表:
public class DefectLocationOutput
{
public string DefectName{ get; set; }
public List<int> TotalCount{ get; set; }
}
这是我的linq查询以填充平面列表
var results = (from def in rep.tblDefects
join defLoc in
(from defDet in rep.tblMovementDefects
join det in rep.tblMovementDetails on defDet.MovementDetailId equals det.MovementDetailId
join loc in rep.tblLocations on det.ToLocationId equals loc.LocationId
join hed in rep.tblMovementHeaders on det.MovementHeaderId equals hed.MovemenHeaderId
where hed.DateCreated >= fromDate && hed.DateCreated <= toDate
select new { loc.LocationName, defDet.DefectId, loc.LocationId }
) on def.DefectId equals defLoc.DefectId
group def by new { def.DefectName, defLoc.LocationId, defLoc.LocationName } into joined
select new
{
LocationName = joined.Key.LocationName,
LocationId = joined.Key.LocationId,
DefectName = joined.Key.DefectName,
TotalCount = joined.Count()
}).OrderBy(x => x.LocationId);
编辑
这就是我想要实现的 以
List<DefectLocationOutput>
的格式,而不是null
值具有0
。
如何才能做到这一点?
我不太了解您在等待什么结果,但这也许会帮助您:
DefectLocationCount cl1 = new DefectLocationCount()
{
DefectName = "Name1",
LocationName = "Location1",
TotalCount = 2
};
DefectLocationCount cl2 = new DefectLocationCount()
{
DefectName = "Name1",
LocationName = "Location2",
TotalCount = 3
};
DefectLocationCount cl3 = new DefectLocationCount()
{
DefectName = "Name2",
LocationName = "Location3",
TotalCount = 6
};
var lstCl = new List<DefectLocationCount>();
lstCl.Add(cl1);
lstCl.Add(cl2);
lstCl.Add(cl3);
var result = lstCl.GroupBy(x => x.DefectName).Select(x => new DefectLocationOutput() { DefectName = x.Key, TotalCount = lstCl.Where(y => y.DefectName == x.Key).Select(y => y.TotalCount).ToList() });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.