日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Linq distinct去重方法之一

發布時間:2024/4/17 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linq distinct去重方法之一 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
var?result?=?query.Distinct().ToList(); List<DeliveryOrderViewModel> dov?=?result.GroupBy( p?=>?new?{p.SAP_DeliveryOrderID}).Select( g?=>?g.First()).ToList(); return?dov;一、使用Distinct()擴展方法去重
?
實例:根據Id去重
錯誤的方式
?


? ? List<Product> products = new List<Product>()
? ? {
? ? ? ? new Product(){ Id="1", Name="n1"},
? ? ? ? new Product(){ Id="1", Name="n2"},
? ? ? ? new Product(){ Id="2", Name="n1"},
? ? ? ? new Product(){ Id="2", Name="n2"},
? ? };


? ? var distinctProduct = products.Distinct();


返回4條數據,因為Distinct 默認比較的是Product對象的引用
?
正確的方式
新建類ProductIdComparer,繼承 IEqualityComparer<Product>,實現Equals方法
?
?
C# 代碼? ?復制


public class ProductIdComparer : IEqualityComparer<Product>
{
? ? public bool Equals(Product x, Product y)
? ? {
? ? ? ? if (x == null)
? ? ? ? ? ? return y == null;
? ? ? ? return x.Id == y.Id;
? ? }


? ? public int GetHashCode(Product obj)
? ? {
? ? ? ? if (obj == null)
? ? ? ? ? ? return 0;
? ? ? ? return obj.Id.GetHashCode();
? ? }
}
?
使用的時候,只需要


var distinctProduct = allProduct.Distinct(new ProductIdComparer());
?
備注:現在假設我們要 按照 Name來篩選重復呢?則需要再添加一個類ProductNameComparer.
?
二、使用GroupBy方式去重
對需要Distinct的字段進行分組,取組內的第一條記錄這樣結果就是Distinct的數據了。
例如
?




List<Product> distinctProduct = allProduct


? .GroupBy(p => new {p.Id, p.Name} )


? .Select(g => g.First())


? .ToList();


?
三、通過自定義擴展方法DistinctBy實現去重
?
?
C# 代碼? ?復制




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;


? ? ? ? }


? ? }


}


方法的使用
1、針對ID,和Name進行Distinct
var query = allProduct.DistinctBy(p => new { p.Id, p.Name });
2、僅僅針對ID進行distinct:
var query = allProduct.DistinctBy(p => p.Id);

轉載于:https://www.cnblogs.com/jhxk/articles/9789336.html

總結

以上是生活随笔為你收集整理的Linq distinct去重方法之一的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。