C#LINQ - 如何区分两个属性但保留类中的所有属性

Fre*_*ter 1 c# collections distinct

我有一个类的集合,集合中的每个类都有三个属性,但需要通过类集合中的两个属性来区分.令人困惑的部分是我只需要两个属性后就需要所有三个属性.最常见的例子是使用你想要区分的属性来创建一个不同类型,但这将摆脱我的第三个属性,我需要在不同操作之后的项目集合中.如何区分三个属性中的两个,但最终结果是包含所有三个属性的类的集合?课程是:

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();
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

spe*_*der 6

如果你看一下.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
    }
Run Code Online (Sandbox Code Playgroud)

如果你看一下!NO_HASHSET实现...请注意源中的元素是如何变换的...

就个人而言,我完全避免使用morelinq来解决这个问题,直接使用第二个实现:

allItems.GroupBy(i => new{i.PropertyOne, i.PropertyTwo}).Select(g => g.First())
Run Code Online (Sandbox Code Playgroud)