NET问答: 如何按属性进行 Distinct() ?
咨詢區(qū)
Patrick Desjardins:
我現(xiàn)在正在學(xué)習(xí) LINQ,對(duì)一個(gè)簡(jiǎn)單類型的 List 進(jìn)行 Distinct() 是非常簡(jiǎn)單的,如 List<int> 或 List<string>,但如果對(duì)復(fù)雜類型 List<T> 的某一個(gè)或者多個(gè)屬性進(jìn)行 Distinct() 的話,該如何做呢?
比如下面的 Person 類:
public?class?Person{public?int?Id?{?get;?set;?}public?string?Name?{?get;?set;?}}List<Person> 內(nèi)容如下。
Person1:?Id=1,?Name="Test1" Person2:?Id=1,?Name="Test1" Person3:?Id=2,?Name="Test2"現(xiàn)在我如何通過 ID 對(duì) List<Person> 進(jìn)行去重呢?最終我想要的結(jié)果是: person1 和 person3。
回答區(qū)
Amy B:
如果你想對(duì) Person 中的一個(gè)或者多個(gè)屬性進(jìn)行去重,很簡(jiǎn)單,可以對(duì)它們進(jìn)行分組,然后在每個(gè)組上選擇一個(gè) 贏家 即可。
List<Person>?distinctPeople?=?allPeople.GroupBy(p?=>?p.PersonId).Select(g?=>?g.First()).ToList();如果基于多個(gè)屬性進(jìn)行去重,可以使用 匿名類型。
List<Person>?distinctPeople?=?allPeople.GroupBy(p?=>?new?{p.PersonId,?p.FavoriteColor}?).Select(g?=>?g.First()).ToList();Jon Skeet:
如果你想實(shí)現(xiàn) distinct-by 的效果,其實(shí)自己實(shí)現(xiàn)一個(gè)就可以了,寫起來(lái)也非常簡(jiǎn)單。
public?static?IEnumerable<TSource>?DistinctBy<TSource,?TKey>(this?IEnumerable<TSource>?source,?Func<TSource,?TKey>?keySelector) {HashSet<TKey>?seenKeys?=?new?HashSet<TKey>();foreach?(TSource?element?in?source){if?(seenKeys.Add(keySelector(element))){yield?return?element;}} }有了這個(gè)方法后,現(xiàn)在可以根據(jù) Id 屬性進(jìn)行去重了。
var?query?=?people.DistinctBy(p?=>?p.Id);如果是基于多個(gè)屬性的話,使用合適的 匿名類型。
var?query?=?people.DistinctBy(p?=>?new?{?p.Id,?p.Name?});點(diǎn)評(píng)區(qū)
其實(shí) distinct-by 是一個(gè)非常實(shí)用的功能,原生的 Linq 不提供支持還是有點(diǎn)可惜的, 我記得以前為了實(shí)現(xiàn)此功能還特意讓 類 實(shí)現(xiàn) IEquatable 接口實(shí)現(xiàn)類型自定義,代碼如下:
public?class?Person?:?IEquatable<Person>{public?int?Id?{?get;?set;?}public?string?Name?{?get;?set;?}public?bool?Equals(Person?other){throw?new?NotImplementedException();}}對(duì)了,如果你覺得 Linq 用的不夠爽,可以使用第三方的 Linq 擴(kuò)展版:MoreLinq,官方地址:https://github.com/morelinq/MoreLINQ
原文鏈接:https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property
總結(jié)
以上是生活随笔為你收集整理的NET问答: 如何按属性进行 Distinct() ?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF 如何将IconFont图标转成G
- 下一篇: 一年增加1.2w星,Dapr能否引领云原