简体   繁体   中英

LINQ Create a nested List

I am trying to convert a flat list to nested list.

This is my flat list:

public class DefectLocationCount {
    public string LocationName { get; set; }
    public string DefectName { get; set; }
    public int TotalCount { get; set; }
}

This is my nested list:

public class DefectLocationOutput
{
    public string DefectName{ get; set; }
    public List<int> TotalCount{ get; set; }
}

This is my linq query to populate the flat list

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

Edit

This is what i am trying to achieve 在此处输入图片说明 In the format of List<DefectLocationOutput> and instead of null values have 0 .

How can this be done?

I didn't really understand what result are you awaiting, but maybe this will help you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM