- Хроники. - -
Фильтр одинаковых объектов в LINQ.
Posted By Ikutsin On 26 февраля 2009 @ 13:47 In .NET C# | Comments Disabled
Часто возникает потребность отфильтровать одинаковые элементы в списке. В LINQ есть метод Distinct, который получает интерфейс IEqualityComparer. Не совсем понятно, почему метод не может получать lamda-выражение. Следующий код должен исправить положение:
class EqualityComparer : IEqualityComparer
{
public Func DistinctDelegate;
public bool Equals(T x, T y)
{
return DistinctDelegate(x).ToString() == DistinctDelegate(y).ToString();
}
public int GetHashCode(T obj)
{
return obj.ToString().ToLower().GetHashCode();
}
}
public static IEnumerable Distinct(this IEnumerable coll, Func distinctDelegate)
{
EqualityComparer myd = new EqualityComparer();
myd.DistinctDelegate = distinctDelegate;
return coll.Distinct(myd);
}
public static IQueryable Distinct(this IQueryable coll, Func distinctDelegate)
{
EqualityComparer myd = new EqualityComparer();
myd.DistinctDelegate = distinctDelegate;
return coll.Distinct(myd);
}
Первый метод используется для Linq2Object, второй — Linq2SQL.
Использование:
var words = from x in new[] { "dog", "cat", "cat" } select new { Word = x };
var distinctWords = words.Distinct(x => x.Word);
Код предоставил Владимир Калошин.
Article printed from Хроники.:
URL to article: /860-filtr-odinakovyx-obektov-v-linq
Click here to print.
Copyright © 2008 Все, что меня окружает. All rights reserved.