简体   繁体   中英

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

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

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

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