我将多个List聚合到一个List中,并希望根据Foo(Foo.Prop1)的一个属性使其不同。我无权修改Foo的Equality比较器。
Dictionary<string, List<Foo>> fooDictionary = new Dictionary<string, List<Foo>>();
List<Foo> foovals = (from e in fooDictionary
where e.Key == "foo1" || e.Key == "foo2" || e.Key == "foo3"
select e.Value).SelectMany(f => f).ToList();
这里唯一缺少的是最后的.Distinct(),以使Foo独一无二,但是,在我的情况下,我无法修改有关Foo的任何内容,所以简单地调用Distinct()将无效。
有没有办法修改此查询以返回基于Foo.Prop1的区别?
答案 0 :(得分:3)
您可以将自定义相等比较器传递给Distinct()
:
.SelectMany().Distinct(new FooEqualityComparer());
在新文件中,“Foo EqualityComparer.csp>
public class FooEqualityComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo x, Foo y)
{
return Equals(x.Prop1, y.Prop1);
}
public int GetHashCode(Foo x)
{
return x.Prop1.GetHashCode();
}
}
答案 1 :(得分:2)
您可以使用DistinctBy
中的MoreLINQ方法:
var query = fooVals.DistinctBy(foo => foo.Property1);
答案 2 :(得分:0)
var tempKeys = new HashSet<int>(); // change int to the actual type of Prop1
List<Foo> foovals = (from e in fooDictionary
where e.Key == "foo1" || e.Key == "foo2" || e.Key == "foo3"
select e.Value).SelectMany(f => f)
.Where(f => tempKeys.Add(f.Prop1))
.ToList();