removing duplicates in a list with linq

后端 未结 3 2116
日久生厌
日久生厌 2020-12-15 05:22

Suppose you have a list of MyObject like this:

public class MyObject
{
  public int ObjectID {get;set;}
  public string Prop1 {get;set;}
}

3条回答
  •  我在风中等你
    2020-12-15 05:48

    You can use GroupBy() and select the first item of each group to achieve what you want - assuming you want to pick one item for each distinct ObjectId property:

    var distinctList = myList.GroupBy(x => x.ObjectID)
                             .Select(g => g.First())
                             .ToList();
    

    Alternatively there is also DistinctBy() in the MoreLinq project that would allow for a more concise syntax (but would add a dependency to your project):

    var distinctList = myList.DistinctBy( x => x.ObjectID).ToList();
    

提交回复
热议问题