C# Linq statements or a foreach() for totalling subsets?

c#, foreach, linq

Solution

Both of these examples have duplicated code, and both aren't ready for a change on `Type` - what if it had three values? What if it had 30? You could use linq to group by it and get the total:

var totals = from p in exampleList
             group p by p.Type into g
             select new { Type = g.Key, Total = g.Sum(p => p.Total ) };

So `totals` is a collection of objects with the properties `Type` and `Total`

Problem

Which of these solutions is preferred? For a List: ``` List<ExampleInfo> exampleList = new List<ExampleInfo>(); public class ExampleInfo { internal ExampleInfo() { } /* Business Properties */ public int Id { get; set; } public string Type { get; set; } public decimal Total { get; set; } } ``` I wish to get subtotals based off the 'Total' value. Option 1: ``` var subtotal1 = exampleList.Where(x => x.Type == "Subtype1").Sum(x => x.Total); var subtotal2 = exampleList.Where(x => x.Type == "Subtype2").Sum(x => x.Total); ``` Option 2: ``` decimal subtotal1 = 0m; decimal subtotal2 = 0m; foreach (ExampleInfo example in exampleList) { switch (example.Type) { case "Subtype1": subtotal1 += example.Total; break; case "Subtype2": subtotal2 += example.Total; break; default: break; } } ``` The list will be <10 items in most cases. Edit: Chris raised a very good point I did not mention. The program is already using .NET Framework 3.5 SP1 so compatibility isn't an important consideration here.

Original source