LINQ创建嵌套列表

时间:2016-04-28 08:06:29

标签: c# .net linq

我正在尝试将平面列表转换为嵌套列表。

这是我的单位清单:

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);

修改

这就是我想要实现的目标 enter image description here 格式为List<DefectLocationOutput>而不是null值为0

如何做到这一点?

1 个答案:

答案 0 :(得分:2)

我真的不明白你在等什么结果,但也许这会对你有所帮助:

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() });
相关问题