今晚看了一篇前辈写的linq对集合元素合并去重复处理,觉得有点麻烦,原文地址如下:
于是我自己琢磨利用linq的分组函数,重新写了一个方法,代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication4{class Program{static void Main(){ ListlistProduct = new List { new Product{StockNum=1,ProductNo="01",Tag="a"}, 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"}, }; List listProduct2 = new List (); var group = listProduct.GroupBy(p=>p.ProductNo); foreach (IGrouping groupSequence in group) { Product p2= new Product { ProductNo=groupSequence.First().ProductNo, StockNum=groupSequence.Sum(p=>p.StockNum) , Tag=string.Join(",",groupSequence.Select(t => t.Tag).ToArray()) }; listProduct2.Add(p2); }//输出验证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; }}}