Right, so I have an enumerable and wish to get distinct values from it.
Using System.Linq
, there\'s of course an extension method called Distinct<
To Wrap things up . I think most of the people which came here like me want the simplest solution possible without using any libraries and with best possible performance.
(The accepted group by method for me i think is an overkill in terms of performance. )
Here is a simple extension method using the IEqualityComparer interface which works also for null values.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable DistinctBy(this IEnumerable items, Func property)
{
GeneralPropertyComparer comparer = new GeneralPropertyComparer(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer : IEqualityComparer
{
private Func expr { get; set; }
public GeneralPropertyComparer (Func expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}