Search code examples
linqasp.net-core

Linq - Grouping a list and get more than one data from it


I have a timetable list. I want to pull two data by grouping over this list. However, I was not successful. My data.

id xid date yid gid
1 30 2022-08-19 5 3
2 31 2022-08-18 6 5
3 30 2022-08-17 6 3
4 32 2022-08-18 6 5

My code

_contex.timetable.where(i=>i.yid==6).DistinctBy(i => i.xid).Select(i => new { i.xid, i.gid, i.date}).ToListAsync();

but null value or error. What i want to do.

xid date yid gid
30 2022-08-19 5 3
31 2022-08-18 6 5
32 2022-08-18 6 5

I want to get the last data of the date and also the gid fields.

Sorry for my bad English, I hope I explained.


Solution

  • From your question, I think you want to get the data of Id,date,gid from latest date row which group by xid, So you can try to refer this code:

    var result = await _context.timetables.GroupBy(x => x.xid)
                  .Select(y => y.OrderByDescending(r => r.date)
                   .Select(a=> new {a.Id,a.date,a.gid}).FirstOrDefault())
                    .ToListAsync();
    

    enter image description here