问题
I want to remove the duplicates based on a property of my object:
public class MyType
{
public string _prop1;
public string _prop2;
public LocationsClass(string prop1, string prop2)
{
_prop1= prop1;
_prop2= prop2;
}
}
...
List<MyType> myList;
So basically I want to remove all MyType objects from myList, with the same value in _prop1. Is there a way to do this, probably with LINQ?
回答1:
var distinctItems = myList.GroupBy(x => x.prop1).Select(y => y.First());
回答2:
You can also use morelinq DistinctBy:
distinctItems = myList.DistinctBy(x => x.prop1).ToList();
or with several properties:
distinctItems = myList.DistinctBy(x=> new { x.prop1, x.prop2}).ToList();
来源:https://stackoverflow.com/questions/30434426/how-to-remove-duplicates-from-a-list-of-custom-objects-by-a-property-of-the-obj