JustLearning
JustLearning

Reputation: 3322

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 enter image description here In the format of List<DefectLocationOutput> and instead of null values have 0.

How can this be done?

Upvotes: 1

Views: 1102

Answers (1)

Julia
Julia

Reputation: 174

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

Upvotes: 3

Related Questions