How to remove duplicates from a list of custom objects, by a property of the object [duplicate]

末鹿安然 提交于 2020-05-13 14:52:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!