集团与总结列表<对象[]> [英] Group and Sum a List<object[]>

查看:99
本文介绍了集团与总结列表<对象[]>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的列表<对象[]>

List<object[]> olst = new List<object[]>();

olst.Add(new object[] { "AA1", 1 });
olst.Add(new object[] { "AA2", 1 });
olst.Add(new object[] { "AA2", 1 });
olst.Add(new object[] { "AA1", 1 });
olst.Add(new object[] { "AA1", 1 });

olst ,我需要制作新的列表<对象> 持有这样的:

From olst, I need to produce a new List<object> to hold this:

"AA1", 3
"AA2", 2

在换句话说,我需要组的 olst [X] [0] 并总结 olst [X] [1]

我可以用一个for循环,但我希望有人能。使用lambda表达式和/或LINQ来完成这个帮助我

In other words, I need to group olst[x][0] and sum up olst[x][1].
I could use a for loop, but I was hoping someone could help me using lambda expressions and/or linq to accomplish this.

推荐答案

使用的 GROUPBY 和的 选择

List<object[]> newList = olst
    /* Group the list by the element at position 0 in each item */
    .GroupBy(o => o[0].ToString())
    /* Project the created grouping into a new object[]: */
    .Select(i => new object[]
    {
        i.Key,
        i.Sum(x => (int)x[1])
    })
    .ToList();

这篇关于集团与总结列表&LT;对象[]&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆