I have a class Person with properties (dni, Name, lastname, Adate(dd/mm/yyyy)). The List of Person is populated with duplicated items.
12345 Jhon scofield 7/10/2015
24627 Liz Pereira 7/06/2014
32313 Brian O'conner 12/06/2012
12345 Jhon scofield 7/10/2016
32313 Brian O'conner 12/06/2015
i try:
var x = ListFamily.GroupBy(p => p.dni).OrderByDescending(t => t.Adate)
.FirstOrDefault();
but t.Adate is not recognize
var y = ListFamily.OrderBy(z => z.Adate).First();
but this return only one family object.
How to remove the duplicates person using latest date in the list with linq (lambda expression)? i mean, i want to return a list without duplicates dnis and show the person with latest date like this
24627 Liz Pereira 7/06/2014
12345 Jhon scofield 7/10/2016
32313 Brian O'conner 12/06/2015
You need to project the grouping rows for each group to select the record with the highest date using OrderByDescensing
with Select
after GroupBy
like :
var x = ListFamily.GroupBy(p => p.dni)
.Select(g=>g.OrderByDescending(x=>x.Adate)
.FirstOrDefault()
);
You could do this:
var result= ListFamily.GroupBy(p => p.dni)
.Select(g=>g.OrderDescending(p=>p.Adate).FirstOrDefault());
You need to order each group in descending order to select the latest.
当您通过GroupBy
获得一个可枚举的组时,因此您需要为每个组选择具有最新日期的条目:
ListFamily.GroupBy(p => p.dni, (_, g) => g.OrderByDescending(x => x.Adate).FirstOrDefault());
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.