简体   繁体   中英

Sum values from a list of string and create a dictionary

I want to calculate and sum all values from a sorted list of string like that

List<string> sortedList = new List<string>();
//name, number, weight
sortedList.Add("A,5,1");
sortedList.Add("A,3,2");
sortedList.Add("B,4,1");
sortedList.Add("B,6,2");

sortedList.Sort();

Input: (List l)

Output: (List<Dicionary<string,int>> result):

A ( (5*1)+ ( 3*2) )
B ( (4*1) + (6*2) )

new List of dictionary <string, int>

1 - dic["A" , 11]
2 - dic["B" , 16]

Using linq you can do this.

Dictionary<string, int> r = sortedList.Select(x => x.Split(','))
    .GroupBy(x => x[0])
    .ToDictionary(x => x.Key, x => x.Sum(y => int.Parse(y[1])*int.Parse(y[2])));

First split all the string by , . then group them by first element of array. then convert them into dictionary. first element is key. and the value is sum of element2*element3

First you need to split string so you can get multiplication and key. You can split using Split method. Also, you need to skip first element after splitting.

var multArray = sortedList.Select (x=>int.Parse (x.Split(',')[1])*int.Parse (x.Split(',')[2]));
var keyArray = sortedList.Select (x=>x.Split(',')[0]);

multArray is array with sums, and keyarray is array with keys. Then you need populate dictionary.

for (int i = 0; i  < keyArray.Count(); i ++) 
{
    if (dictionary.ContainsKey (keyArray[i])) 
    { 
        dictionary[keyArray[i]] += multArray [i];
    } 
    else
    {
        dictionary.Add (keyArray[i], multArray [i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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