3

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?

v.g.
  • 1,076
  • 5
  • 19
  • 38
  • Linq will just get you a filtered list. It will not modify your original myList object - just making sure your expectation is right. – Carbine May 25 '15 at 08:54
  • 2
    http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property, http://stackoverflow.com/questions/11811110/select-distinct-by-two-properties-in-a-list, http://stackoverflow.com/questions/2537823/distinct-by-property-of-class-by-linq – CodeCaster May 25 '15 at 08:54

2 Answers2

16
var distinctItems = myList.GroupBy(x => x.prop1).Select(y => y.First());
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • For smaller collection it is ok to use GroupBy. In other case it should be used with a grain of salt, it creates time complexity and could affect performance. – Sunny Jan 08 '20 at 11:55
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();
Artur Udod
  • 4,465
  • 1
  • 29
  • 58