How to Select Last Record in a Linq Groupby Clause

How to select last record in a LINQ GroupBy clause

You can order you items

Mains.GroupBy(l => l.ContactID)
.Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault())
.ToList()

Get the last record of group using LINQ

Depending on what you want you can change OrderBy or even can use First or Last in this.

list
.OrderByDescending(a => a.ValueA)
.GroupBy(a => a.GroupId)
.Select(g => g.Last());

How to get the latest/last record with a group by clause with NHibernate Linq provider

It's have been a long journey, but now it's over. I hope that I can help someone else in the same situation by answering my own question.

var aendring = from sagsAendring in _session.Query<ViewSagsAendring>()
where sagsAendring.Dato ==
(
from innersagsAendring in _session.Query<ViewSagsAendring>()
where innersagsAendring.SagId == sagsAendring.SagId
select innersagsAendring.Dato
).Max()
select sagsAendring;
var result = aendring.ToList();

And because you can chain linq statements you can build a linq filter like this

 if(Filters.VisInterneAendringer == false)
query = query.Where(x => x.Ekstern == true);
if (Filters.VisKunNyesteAendringer)
{
query = query.Where(sagsAendring => sagsAendring.Dato ==
(
from innerSagsAendring in Session.Query<ViewSagsAendring>() where innerSagsAendring.SagId == sagsAendring.SagId
select innerSagsAendring.Dato
).Max());
}

return query;

C# Group by one property select the newest one from the group

You probably looking for something like that

orders.GroupBy(o => o.CustomerId).Select(g => g.OrderByDescending(o => o.OrderDate).First());

So within each group you will sort by the order date and then select the first one.

Linq query to get the last record

if have to include that you want only non-empty filenames. You may also use ToList() to finalize the query, then FirstOrDefault() should work as expected, try

var tempFileName = objContext.SchedulesAndFiles
.Where(x
=> x.ScheduleId == scheduleId
&& x.Filename != null
&& x.Filename != "")
.OrderByDescending(x => x.ScheduleId)
.Take(1)
.Select(x => x.Filename)
.ToList()
.FirstOrDefault();

LINQ: How to get the Max Id with a group by clause?

You want to pick top record from each group.

var ProcessAudList = ProcessAudService.Where(x => x.Active == "Y")
.GroupBy(x => x.ProjectSeq, (key,g)=>g.OrderByDescending(e=>e.ProjectValue).First());

Check demo code



Related Topics



Leave a reply



Submit