我知道有两种方法可以从支持显式比较的对象数组中删除双打:
如何从结构数组中删除双精度数,仅将数组成员与单个字段进行比较?换句话说,如何编写可以由Distinct()使用的谓词。
此致
答案 0 :(得分:5)
好吧,你可以实现IEqualityComparer<T>
来挑选该字段并将其用于相等测试和散列...或者你可以使用DistinctBy
MoreLINQ 3}}
当然,您不必非常依赖MoreLINQ - 您可以非常简单地实现它:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
// TODO: Implement null argument checking :)
HashSet<TKey> keys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
答案 1 :(得分:3)
我可能只是循环:
var values = new HashSet<FieldType>();
var newList = new List<ItemType>();
foreach(var item in oldList) {
if(hash.Add(item.TheField)) newList.Add(item);
}
答案 2 :(得分:2)
之前发布过LINQ答案。我正在复制Richard Szalay的回答:Filtering duplicates out of an IEnumerable
public static class EnumerationExtensions
{
public static IEnumerable<TSource> Distinct<TSource,TKey>(
this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
KeyComparer comparer = new KeyComparer(keySelector);
return source.Distinct(comparer);
}
private class KeyComparer<TSource,TKey> : IEqualityComparer<TSource>
{
private Func<TSource,TKey> keySelector;
public DelegatedComparer(Func<TSource,TKey> keySelector)
{
this.keySelector = keySelector;
}
bool IEqualityComparer.Equals(TSource a, TSource b)
{
if (a == null && b == null) return true;
if (a == null || b == null) return false;
return keySelector(a) == keySelector(b);
}
int IEqualityComparer.GetHashCode(TSource obj)
{
return keySelector(obj).GetHashCode();
}
}
}
正如理查德所说的那样,就像这样使用:
var distinct = arr.Distinct(x => x.Name);
答案 3 :(得分:1)
实施自定义IEqualityComparer<T>
public class MyStructComparer : IEqualityComparer<MyStruct>
{
public bool Equals(MyStruct x, MyStruct y)
{
return x.MyVal.Equals(y.MyVal);
}
public int GetHashCode(MyStruct obj)
{
return obj.MyVal.GetHashCode();
}
}
然后
var distincts = myStructList.Distinct(new MyStructComparer());