using System;using System.Collections.Generic;using System.Linq;namespace LinqTest{ class Program { static void Main() { ListlistProduct = new List { new Product{StockNum=1,ProductNo="01",Tag="a"}, new Product{StockNum=1,ProductNo="01",Tag="a"}, new Product{StockNum=1,ProductNo="01",Tag="a"}, new Product{StockNum=2,ProductNo="01",Tag="b"}, new Product{StockNum=2,ProductNo="01",Tag="b"}, new Product{StockNum=2,ProductNo="01",Tag="b"}, new Product{StockNum=3,ProductNo="02",Tag="c"}, new Product{StockNum=4,ProductNo="02",Tag="d"}, new Product{StockNum=5,ProductNo="03",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(); } } /// /// 产品实体类 /// class Product { ////// 库存 /// public int StockNum { set; get; } ////// 产品编号 /// public String ProductNo { set; get; } ////// 附属标签 /// public String Tag { set; get; } } ////// 去"重复"时候的比较器(只要ProductNo相同,即认为是相同记录) /// class ProductNoComparer : IEqualityComparer{ 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 0; return p.ProductNo.GetHashCode(); } }}