makitocode
makitocode

Reputation: 948

Filter List using linq for remove duplicates items

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

Upvotes: 0

Views: 574

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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()
                         );

Upvotes: 2

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

When you GroupBy you get an enumerable of groups, so you need to select for each group the entry with the latest date:

ListFamily.GroupBy(p => p.dni, (_, g) => g.OrderByDescending(x => x.Adate).FirstOrDefault());

Upvotes: 0

ocuenca
ocuenca

Reputation: 39326

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.

Upvotes: 1

Related Questions