Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique ID records from a List<T> of a collection

Tags:

c#

asp.net

linq

I got the following piece of code:

public class Collect
{
     public string name{ get; set; }
     public int id { get; set; }
     public DateTime registerDate { get; set; }
}

public class ControllingMyList
{

    public void prepareList()
    {
        List<Collect> list = new List<Collect>();

        list= loadList();

        //Rest of the opperations
    }
}

Considering that my loadList method returns for me many duplicated records (id variable) I want to get only one record by ID.

The Distinct() function seems to be a good solution but if I remember correctly, Distinct() filters all the members of the object so just because of a second of difference from "registerDate" variable is considered a criteria to make it distinct, even if its with the same ID.

like image 355
Dan-SP Avatar asked Dec 13 '22 07:12

Dan-SP


2 Answers

    var list= loadList();

    list = list 
        .GroupBy(i => i.id)
        .Select(g => g.First())
        .ToList();
like image 134
sehe Avatar answered Dec 28 '22 13:12

sehe


You have several options:

  • Use DistinctBy() extension method from the MoreLinq project
  • Use the Distinct() overload that accepts a custom equality comparer, and implement a custom comparer
  • Use Linq GroupBy( x=> x.id) and then take the first item of each group.
like image 20
BrokenGlass Avatar answered Dec 28 '22 14:12

BrokenGlass