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=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(); } } /// <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 0; return p.ProductNo.GetHashCode(); } } }