See following code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace t1
{
class MyClass
{
public int? property {get; set;}
public int ID {get; set;}
}
class MyClassComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass x, MyClass y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.property == y.property;
}
public int GetHashCode(MyClass myObject)
{
if (Object.ReferenceEquals(myObject, null)) return 0;
int hashObjectProperty = myObject.property == null ? 0 : myObject.property.GetHashCode();
return hashObjectProperty;
}
}
class Program
{
static void Main()
{
List<MyClass> list = new List<MyClass>();
Console.WriteLine("\nOriginal list:");
foreach(int i in Enumerable.Range(1,10))
{
list.Add(new MyClass{ ID = i, property = (i & 1)});
Console.WriteLine("{0} => {1}", i, i & 1);
}
Console.WriteLine("\nDistinct by property:");
foreach(MyClass myObject in list.Distinct(new MyClassComparer()))
{
Console.WriteLine("{0} => {1}", myObject.ID, myObject.property);
}
Console.ReadKey();
}
}
}
As you will see if you run it,
IEnumerble.Distinct
will do the job for you with the help of a proper comparer, but it will leave the first occurrences. Thus, as I mentioned in my comment, you need to define the comparison means by implementing a proper
IEqualityComparer[
^] - this one could also help you:
A Generic IEqualityComparer for Linq Distinct()[
^]