标签:
今晚看了一篇前辈写的linq对集合元素合并去重复处理,觉得有点麻烦,原文地址如下:http://www.cnblogs.com/yjmyzz/archive/2012/12/18/2823170.html#undefined。
于是我自己琢磨利用linq的分组函数,重新写了一个方法,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main()
{
List<Product> listProduct = new List<Product> {
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<Product> listProduct2 = new List<Product>();
var group = listProduct.GroupBy(p=>p.ProductNo);
foreach (IGrouping<string,Product> 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();
}
}
/// <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; }
}
}
标签:
原文地址:http://www.cnblogs.com/527289276qq/p/4320997.html