哪种解决方案更受青睐?
对于列表:
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; } }
我希望根据“总计”值得到小计.
选项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);
选项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; } }
在大多数情况下,该列表将是< 10项. 编辑:克里斯提出了一个非常好的观点我没有提到.该程序已经在使用.NET Framework 3.5 SP1,因此兼容性不是一个重要的考虑因素.