C#循环通过字典和求和键的值

时间:2016-04-21 19:12:57

标签: c# dictionary

我有Dictionary<string, decimal?>,我希望能够通过不同的字符串对小数进行求和。所以说我在字典中有以下输入,

“1”,20.00 “1”,35.00 “2”,10.00 “3”,15.00 “3”,30.00

我希望以下输出到新词典

“1”,55.00 “2”,10.00 “3”,45.00

我猜它会像

foreach(var item in dictionary)
{
newDictionary.Add(not sure what would go here, maybe some sort of linq query for distinct and sum?);
}

4 个答案:

答案 0 :(得分:2)

假设键值对的列表与其他答案相同:

var myList = New List<KeyValuePair<string, decimal?>> {
    new KeyValuePair<string, decimal?>("1", (decimal)10.00),
    new KeyValuePair<string, decimal?>("1", (decimal)15.00),
    new KeyValuePair<string, decimal?>("2", (decimal)20.00),
    new KeyValuePair<string, decimal?>("3", (decimal)30.50),
    new KeyValuePair<string, decimal?>("3", (decimal)17.500)
};

var myResults = myList.GroupBy(p => p.Key)
                      .ToDictionary(g => g.Key, g=>g.Sum(p=>p.Value))

答案 1 :(得分:1)

字典中的键不能重复,因此2个第一个条目不适合字典。

我想你可能有一个可以循环的对象列表,然后你可以使用字典存储每个&#34;键的总数&#34;

类似

 Dictionary<string, double> totals = new Dictionary<string, double>();
        List<Tuple<string, double>> entries = new List<Tuple<string, double>>() {
            new Tuple<string, double>("1",20.00),
            new Tuple<string, double>("1",35.00),
            new Tuple<string, double>("2",10.00),
            new Tuple<string, double>("3",15.00),
            new Tuple<string, double>("3",30.00)
        };
        foreach (var e in entries)
        {
            if (!totals.Keys.Contains(e.Item1))
            {
                totals[e.Item1] = 0;
            }
            totals[e.Item1] += e.Item2;
        }

答案 2 :(得分:0)

您不能拥有包含重复键的Dictionary对象。当您尝试将现有键添加到Dictionary对象时,您会看到ArgumentException。 请参阅:https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

答案 3 :(得分:0)

如上所述,如果使用相同的密钥,则不能使用Dictionary,因为它们必须是唯一的。 您可以使用最接近字典的KeyPair列表,然后您的代码将如下所示:

        List<KeyValuePair<string, decimal?>> myList = new List<KeyValuePair<string, decimal?>>();

        myList.Add(new KeyValuePair<string, decimal?>("1", (decimal)10.00));
        myList.Add(new KeyValuePair<string, decimal?>("1", (decimal)15.00));
        myList.Add(new KeyValuePair<string, decimal?>("3", (decimal)30.50));
        myList.Add(new KeyValuePair<string, decimal?>("3", (decimal)17.500));

        Dictionary<string, decimal?> sums = new Dictionary<string, decimal?>(); //This can be a dictionary because the keys will be unique after grouping 

        foreach (var item in myList.GroupBy(m => m.Key))
        {
            string currentKey = item.FirstOrDefault().Key;
            sums.Add(currentKey, myList.Where(j => j.Key == currentKey).Sum(o => o.Value));
        }