Monzingo
Monzingo

Reputation: 411

C# Looping through Dictionary and summing values for Keys

I have a Dictionary<string, decimal?>, and i would like to be able to sum the decimals by distinct string. So say i have the below inputs in dictionary,

"1", 20.00 "1", 35.00 "2", 10.00 "3", 15.00 "3", 30.00

I would like the following output to a new Dictionary

"1", 55.00 "2", 10.00 "3", 45.00

I'm guessing it would be something like

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

Upvotes: 2

Views: 3776

Answers (4)

Mr.Mindor
Mr.Mindor

Reputation: 4129

Assuming the same List of key value pairs as in the other answers:

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

Upvotes: 2

Ziv Weissman
Ziv Weissman

Reputation: 4536

As mentioned here You can't use Dictionary if you are using same keys, because they must be Unique. You can use list of KeyPair though, which is closest to Dictionary, then you're code will look like this:

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

Upvotes: 0

Yuvaraj Gunisetti
Yuvaraj Gunisetti

Reputation: 9

You can not have Dictionary object with duplicate keys. You would see ArgumentException when you try to add an existing key into the Dictionary object. Refer: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

Upvotes: 0

Fernando Gutierrez
Fernando Gutierrez

Reputation: 439

The keys in a dictionary can't be repeated, so the 2 first entries won't fit in a dictionary.

I think you may have a list of objects that you can loop, then you can use a dictionary to store the total for each "key"

something like

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

Upvotes: 1

Related Questions