LINQ Distinct()

using System;
using System.Collections.Generic;
using System.Linq; namespace LinqTest
{
class Program
{ static void Main()
{
List<Product> listProduct = new List<Product> {
new Product{StockNum=,ProductNo="",Tag="a"},
new Product{StockNum=,ProductNo="",Tag="a"},
new Product{StockNum=,ProductNo="",Tag="a"},
new Product{StockNum=,ProductNo="",Tag="b"},
new Product{StockNum=,ProductNo="",Tag="b"},
new Product{StockNum=,ProductNo="",Tag="b"},
new Product{StockNum=,ProductNo="",Tag="c"},
new Product{StockNum=,ProductNo="",Tag="d"},
new Product{StockNum=,ProductNo="",Tag="e"},
}; //去重复
var listProduct1 = listProduct.Select(s => new
Product
{
StockNum = s.StockNum,
ProductNo = s.ProductNo,
Tag = s.Tag
}).Distinct(new ProductNoComparer()).ToList(); //输出验证
listProduct1.ForEach(c =>
{
Console.WriteLine("ProductNo={0},StockNum={1},Tag={2}", c.ProductNo, c.StockNum, c.Tag);
}); Console.WriteLine("-------------------"); //去重复
var listProduct2 = listProduct.Select(s => new
{
s.ProductNo,
s.StockNum,
s.Tag
}).Distinct().ToList(); //输出验证
listProduct2.ForEach(c =>
{
Console.WriteLine("ProductNo={0},StockNum={1},Tag={2}", c.ProductNo, c.StockNum, c.Tag);
});
Console.Read();
} } /// <summary>
/// 产品实体类
/// </summary>
class Product
{
/// <summary>
/// 库存
/// </summary>
public int StockNum { set; get; } /// <summary>
/// 产品编号
/// </summary>
public String ProductNo { set; get; } /// <summary>
/// 附属标签
/// </summary>
public String Tag { set; get; }
} /// <summary>
/// 去"重复"时候的比较器(只要ProductNo相同,即认为是相同记录)
/// </summary>
class ProductNoComparer : IEqualityComparer<Product>
{
public bool Equals(Product p1, Product p2)
{
if (p1 == null)
return p2 == null;
return p1.ProductNo == p2.ProductNo && p1.StockNum == p2.StockNum && p1.Tag == p2.Tag;
} public int GetHashCode(Product p)
{
if (p == null)
return ;
return p.ProductNo.GetHashCode();
}
}
}
上一篇:Spring Cloud Eureka 自我保护机制


下一篇:linq Distinct 自定义去重字段