Linq查询问题:基于对象属性的区别(Linq query question: Distinct based on object's property)

编程入门 行业动态 更新时间:2024-10-17 15:29:11
Linq查询问题:基于对象属性的区别(Linq query question: Distinct based on object's property)

我正在将多个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的项目Distinct?

I am aggregating multiple List's into one List and would like to make it distinct based on one of the properties of Foo (Foo.Prop1).. I do not have access to modify Foo's Equality comparer.

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();

the only thing missing here is the .Distinct() at the end, to make Foo's unique, however, in my case, i can't modify anything about Foo, so simply calling Distinct() will not work.

Is there a way to modify this query to return items Distinct based on Foo.Prop1 ?

最满意答案

您可以在MoreLINQ中使用DistinctBy方法:

var query = fooVals.DistinctBy(foo => foo.Property1);

You could use the DistinctBy method in MoreLINQ:

var query = fooVals.DistinctBy(foo => foo.Property1);

更多推荐

本文发布于:2023-08-07 12:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464489.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   区别   对象   query   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!