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

本文关键字:属性 保留 两个 何区 C#LINQ- | 更新日期: 2023-09-27 18:20:53

我有一个类的集合,集合中的每个类都有三个属性,但需要通过类集合上的两个属性来区分。令人困惑的是,在我只区分了其中两个属性之后,我需要所有三个属性。最明显的例子是,使用您想要区分的属性创建一个匿名类型,但这将消除我的第三个属性,我需要在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();

谢谢你的帮助!

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

如果您查看.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())