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.
var list= loadList();
list = list
.GroupBy(i => i.id)
.Select(g => g.First())
.ToList();
You have several options:
DistinctBy()
extension method from the MoreLinq projectDistinct()
overload that accepts a custom equality comparer, and implement a custom comparerGroupBy( x=> x.id)
and then take the first item of each group.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With