简体   繁体   English

C#-从KeyValuePair列表中删除键重复项并添加值

[英]C# - Remove Key duplicates from KeyValuePair list and add Value

I have a KeyValuePair List in C# formatted as string,int with an example content: 我有一个C#的KeyValuePair列表,格式为string,int ,带有示例内容:

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

Definition Code: 定义代码:

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

Becoming: 变得:

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();
var mylist = new KeyValuePair<string,int>[2];

mylist[0]=new KeyValuePair<string,int>("str1",5);
mylist[1]=new KeyValuePair<string,int>("str1",8);
var output = mylist.GroupBy(x=>x.Key).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Value).Sum());

I would use a different structure: 我会使用不同的结构:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
        dict.Add("test", new List<int>() { 8, 5 });
        var dict2 = dict.ToDictionary(y => y.Key, y => y.Value.Sum());
        foreach (var i in dict2)
        {
            Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);
        }
        Console.ReadLine();
    }
}

The first dictionary should be your original structure. 第一个字典应该是您的原始结构。 To add elements to it check first if key exist, if it exist just add the element to the value list, if it doesn't exist and a new item to the dictionary. 要向其添加元素,请首先检查键是否存在,如果存在,则只需将元素添加到值列表中(如果不存在),然后将新项目添加到字典中。 The second dictionary is just a projection of the first one summing the list of values for each entry. 第二个字典只是第一个字典的投影,该投影将每个条目的值列表相加。

A non-Linq answer: 非Linq答案:

Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in mylist)
{
    if (temp.ContainsKey(item.Key))
    {
        temp[item.Key] = temp[item.Key] + item.Value;
    }
    else
    {
        temp.Add(item.Key, item.Value);
    }
}
List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>(temp.Count);
foreach (string key in temp.Keys)
{
    result.Add(new KeyValuePair<string,int>(key,temp[key]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM