C#-从KeyValuePair列表中删除键重复项并添加值 [英] C# - Remove Key duplicates from KeyValuePair list and add Value

查看:285
本文介绍了C#-从KeyValuePair列表中删除键重复项并添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#的KeyValuePair列表,格式为string,int,并带有示例内容:

I have a KeyValuePair List in C# formatted as string,int with an example content:

mylist[0]=="str1",5
mylist[2]=="str1",8

我想要一些代码来删除其中一项,而在其他项中添加重复值.
就是这样:

I want some code to delete one of the items and to the other add the duplicating values.
So it would be:

mylist[0]=="str1",13

定义代码:

List<KeyValuePair<string, int>> mylist = new List<KeyValuePair<string, int>>();

托马斯,我将尝试用伪代码对其进行解释. 基本上,我要

Thomas, I'll try to explain it in pseudo code. Basically, I want

mylist[x]==samestring,someint
mylist[n]==samestring,otherint

成为:

mylist[m]==samestring,someint+otherint

推荐答案

var newList = myList.GroupBy(x => x.Key)
            .Select(g => new KeyValuePair<string, int>(g.Key, g.Sum(x=>x.Value)))
            .ToList();

这篇关于C#-从KeyValuePair列表中删除键重复项并添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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