Home > Net >  Linq group by with nullable property. unable to skip the object in child list
Linq group by with nullable property. unable to skip the object in child list

Time:08-19

I have Table with 2 reference classes id in it. I wanted to group on ChildClass 2 properties and add child class3 in list if they are not null. I am unable to do how can i put that null check to not add null items in the list

var groupData = await _context.Class1
            .Where(ct => ct.Id == Id                
            && ct.C2 != null )
            .Select(h => new { h.Class2.F1, h.Class2.F2,  h.Class3 }
            ).ToListAsync();
        var result = groupData.GroupBy(g => new { g.F1, g.F2 }).Select(h => new MyResult
        {
            F1 = h.Key.F1,
            F2 = h.Key.F2            
            F4List = h.Select(x =>new MyModel
            {
                C5F1 = x.Class3.F1,
                C5F2 = x.Class3.F2,
                C5F3 = x.Class3.F3,                
            }).ToList()
            
        }).ToList();

have tried

following but it add null item in list instead of skipping those records

var groupData = await _context.Class1
            .Where(ct => ct.Id == Id                
            && ct.C2 != null )
            .Select(h => new { h.Class2.F1, h.Class2.F2,  h.Class3 }
            ).ToListAsync();
        var result = groupData.GroupBy(g => new { g.F1, g.F2 }).Select(h => new MyResult
        {
            F1 = h.Key.F1,
            F2 = h.Key.F2            
            F4List = h.Select(x => x.Class3 != null ? new MyModel
            {
                C5F1 = x.Class3.F1,
                C5F2 = x.Class3.F2,
                C5F3 = x.Class3.F3,                
            }: null).ToList()
            
        }).ToList();

class1 is something like

public class Class1
{
int Id
int class2ID
int? class3ID

virtual Class2
virtual Class3

}

Please let me know what i am missing

CodePudding user response:

if you want to skip the null values, use a WHERE clause:

F4List = h.Where( x => x.Class3 != null )
          .Select( x => new MyModel
            {
                C5F1 = x.Class3.F1,
                C5F2 = x.Class3.F2,
                C5F3 = x.Class3.F3,                
            })
          .ToList()
  • Related