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