简体   繁体   English

从字符串列表中求和并创建字典

[英]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) 输入:(清单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. 使用linq可以做到这一点。

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 值是element2*element3

First you need to split string so you can get multiplication and key. 首先,您需要分割字符串,以便获得乘法和键。 You can split using Split method. 您可以使用Split方法进行Split 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. multArray是具有和的数组,而keyarray是具有键的数组。 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]);
    }
}

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

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