Linq Distinct基于对象的属性

Lie*_*oen 8 linq distinct

是否有可能List根据对象的属性获取a的不同元素List

喜欢: Distinct(x => x.id)

对我来说没有用的是:.Select(x => x.id).Distinct()因为那时我会回来List<int>而不是List<MyClass>

Mar*_*ann 6

这对我来说听起来像是一个分组构造,因为你需要决定你真正想要返回哪个相同的对象

var q = from x in foo
        group x by x.Id into g
        select g.First(); // or some other selection from g
Run Code Online (Sandbox Code Playgroud)

仅仅因为Id在多个项目中是相同的并不意味着这些项目在其他属性上是相同的,因此您需要明确决定返回哪个项目.


jas*_*son 5

你可以做的是实现自己的,IEqualityComparer<T>并将其传递给Distinct:

class SomeType {
    public int id { get; set; }
    // other properties
}
class EqualityComparer : IEqualityComparer<SomeType> {
    public bool Equals(SomeType x, SomeType y) {
        return x.id == y.id;
    }

    public int GetHashCode(SomeType obj) {
        return obj.id.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

// elements is IEnumerable<SomeType>
var distinct = elements.Distinct(new EqualityComparer());
// distinct is IEnumerable<SomeType> and contains distinct items from elements
// as per EqualityComparer
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 2

你需要DistinctBy。它不是标准 .NET 库的一部分,但 Jon Skeet在此处为 Linq to 对象实现了它。它也包含在morelinq中。