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

ぃ、小莉子 提交于 2021-01-28 06:14:51

问题


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

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

回答1:


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



回答2:


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());



回答3:


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.




回答4:


A non-Linq answer:

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]);
}


来源:https://stackoverflow.com/questions/13698127/c-sharp-remove-key-duplicates-from-keyvaluepair-list-and-add-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!