昨天同事问了一个问题,怎么把字典对象组成的List集合进行按code分组,将其qty进行Sum累和。
考虑了C#的Lambda表达对集合的万能性,试了一下,代码如下:
public static void Main(string[] args)
{
TestLambdaGroupBy();
Console.Read();
}
public static void TestLambdaGroupBy()
{
//创建类型为Dictionary<string, object>的List集合,目的是要将同一code的qty进行汇总
var dic1 = new Dictionary<string, object>();
dic1.Add("code", "code1");
dic1.Add("name", "name1");
dic1.Add("qty", 2);
var dic2 = new Dictionary<string, object>();
dic2.Add("code", "code1");
dic2.Add("name", "name1");
dic2.Add("qty", 7);
var dic3 = new Dictionary<string, object>();
dic3.Add("code", "code2");
dic3.Add("name", "name2");
dic3.Add("qty", 5);
var list = new List<Dictionary<string, ob