简体   繁体   中英

How do get last data in group by using linq

In my table i have a property detail. Each property has agent name. I want to group by agent name and take last inserted row of each agent. I used below code but it gives first row values.When i use lastordefault it display error. Any one have any idea

 var property = (from n in properties select n).GroupBy(x => x.agentname)
              .Where(g => g.Count() == 1)
              .Select(g => g.FirstOrDefault()).OrderByDescending(x => x.datecreated).Take(20);

First of all your first query makes no sense to me ie (from n in properties select n) you can directly apply GroupBy on properties . Next, you are selecting first record from the group and applying OrderByDescending on complete result which will do nothing as you have just 1 record.

This should give you expected result:-

var property = properties.GroupBy(x => x.agentname)
                         .Select(x => x.OrderByDescending(z => z.datecreated)
                                       .FirstOrDefault());

This will return a collection containing last inserted row of each agent .

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