Distinct()方法在MSDN中的示例
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}

 

Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 10 },
new Product { Name = "lemon", Code = 9 } };
var lstDistProduct = products.Distinct();
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}

 

但在實際使用中發現往往無法實現篩選出不重複的資料的目的
查找相關資料獲得如下方法:
方法1:使用MoreLinq庫

 

var list1 = products.DistinctBy(x=> x.Code);





foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}

 

方法2:

 

class ProductComparare : IEqualityComparer<product>
{
private Func<Product, object> _funcDistinct;
public ProductComparare(Func<Product, object> funcDistinct)
{
this._funcDistinct = funcDistinct;
}





public bool Equals(Product x, Product y)
{
return _funcDistinct(x).Equals(_funcDistinct(y));
}





public int GetHashCode(Product obj)
{
return this._funcDistinct(obj).GetHashCode();
}
}



var list2 = products.Distinct(new ProductComparare( a => a.Code ));





foreach (Product p in list2)
{
Console.WriteLine(p.Code + " : " + p.Name);
}

 

方法3:

 

List<Product> list = products
.GroupBy(a => a.Code )
.Select(g => g.First())
.ToList();





foreach (Product p in list)
{
Console.WriteLine(p.Code + " : " + p.Name);
}

 

本人通過第三種方法得到了想要的不重復資料。
本文參考文章連結 :HTTP://www.codeproject.com/Articles/535374/DistinctBy-in-Linq-Find-Distinct-object-by-Propert
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()