我有一个类集合,集合中的每个类都有三个属性,但需要通过类集合中的两个属性来区分。令人困惑的部分是我只需要两个属性后就需要所有三个属性。最不同的例子说,使用你想要区分的属性来创建一个不同类型,但这将摆脱我的第三个属性,我需要在不同操作后的项目集合中。如何区分三个属性中的两个,但最终结果是包含所有三个属性的类的集合?等级是:
public class Foo
{
public int PropertyOne {get; set;}
public int PropertyTwo {get; set;}
public string PropertyThree {get; set;}
}
// fake example of what I want but
// final result has all three properties in the collection still
var finalResult = allItems.DistinctBy(i => i.PropertyOne, i.PropertyTwo).ToArray();
感谢您的帮助!
答案 0 :(得分:5)
如果你看implementation of .DistinctBy:
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
#if !NO_HASHSET
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
#else
//
// On platforms where LINQ is available but no HashSet<T>
// (like on Silverlight), implement this operator using
// existing LINQ operators. Using GroupBy is slightly less
// efficient since it has do all the grouping work before
// it can start to yield any one element from the source.
//
return source.GroupBy(keySelector, comparer).Select(g => g.First());
#endif
}
如果你看一下!NO_HASHSET
实现......注意来源的元素是如何产生的......
就个人而言,我完全避免使用morelinq解决这个问题,直接使用第二个实现:
allItems.GroupBy(i => new{i.PropertyOne, i.PropertyTwo}).Select(g => g.First())