Search code examples
c#.net-2.0

How to Add Sub-Totals without LINQ


I work in a place where the in-house clients all have old version of .NET so I need to get by without LINQ. I am trying to achieve something pretty simple. The list of my class looks like this:

List<TestClass> list = new List<TestClass>()
             {
                 new TestClass(){ ThisName= "A", ThisNumber = 12},
                 new TestClass(){ ThisName= "B", ThisNumber = 4},
                 new TestClass(){ ThisName= "A", ThisNumber = 7},
                 new TestClass(){ ThisName= "C", ThisNumber = 14},
                 new TestClass(){ ThisName= "C", ThisNumber = 13},
                 new TestClass(){ ThisName= "B", ThisNumber = 10},
                 new TestClass(){ ThisName= "B", ThisNumber = 8},
                 new TestClass(){ ThisName= "C", ThisNumber = 16},
                 new TestClass(){ ThisName= "A", ThisNumber = 17},
                 new TestClass(){ ThisName= "B", ThisNumber = 11},
             };
             return list;

and the end result should look like this:

A   36
B   33
C   43

with LINQ I would simply write this code:

Dictionary<string, int> dict = source.GroupBy(x => x.ThisName).Select(g => new {Key = g.Key, Value = g.Sum( h => h.ThisNumber)}).ToDictionary(g => g.Key, g => g.Value);

BUT, I have to achieve the same thing without LINQ.

Thank you in advance for any idea.


Solution

  • Without Linq, you can just create your dictionary upfront, and sum the quantities in a foreach:

    Dictionary<string, int> sumDict = new Dictionary<string, int>();
    foreach (var item in list) {
        if (!sumDict.ContainsKey(item.ThisName)) {
            sumDict.Add(item.ThisName, 0);
        }
        sumDict[item.ThisName] += item.ThisNumber;
    }