本文转载:http://www.cnblogs.com/yjmyzz/archive/2012/12/18/2823170.html
今天写代码时,需要对一个数组对象中按一定规则合并、去重处理,不想再毫无新意手动写For循环遍历(天天写一样的代码很没劲),于是依旧linq,发现真心方便:
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=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"},
};
//注:处理目标->将"编号(ProductNo)"相同的产品记录,"库存量(StockNum)"合并,"附属标签(Tag)"合并
//合并处理
listProduct.ForEach(c => {
var group = listProduct.Where(a => a.ProductNo == c.ProductNo);
c.StockNum = group.Sum(x => x.StockNum);
c.Tag = group.Select(t => t.Tag).ToList().Join();
});
//去重复(默认是保留出现相同元素的第一个元素)
listProduct = listProduct.Distinct(new ProductNoComparer()).ToList();
//输出验证
listProduct.ForEach(c =>
{
Console.WriteLine("ProductNo={0},StockNum={1},Tag={2}", c.ProductNo, c.StockNum, c.Tag);
});
//输出结果:
//ProductNo=01,StockNum=3,Tag=a,b
//ProductNo=02,StockNum=7,Tag=c,d
//ProductNo=03,StockNum=5,Tag=e
Console.Read();
}
}
/// <summary>
/// 工具类(一般开发中,可定义在自己的工具类库里)
/// </summary>
static class Utils {
/// <summary>
/// List扩展方法,将List元素用分隔符连接后,返回字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="splitStr"></param>
/// <returns></returns>
public static String Join<T>(this List<T> list, string splitStr=",")
{
string result = string.Empty;
foreach (var item in list)
{
result += item.ToString() + splitStr;
}
return result.Trim(splitStr.ToCharArray());
}
}
/// <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;
}
public int GetHashCode(Product p)
{
if (p == null)
return 0;
return p.ProductNo.GetHashCode();
}
}
}
其它编程语言如果都象C#这般犀利,世界就更美好了