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.
CodePudding user response:
You group them up by xid
and pick the latest date row from each group.
var result = context.timetable
.GroupBy(t => t.xid)
.Select(g => g.OrderByDescending(r => r.date).First())
.ToListAsync();
CodePudding user response:
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();