Linq distinct去重方法之一
阿新 • • 發佈:2019-01-04
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);
例項:根據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);