Saturday, August 29, 2009

How to use list.Sum<> in System.Collections.Generic

List.Sum<>
This will return the summation of named attribute.
List<Item> listItem = new List<Item>();
 
Item T1 = new Item() { Name = "A", Amount = 100 };
Item T2 = new Item() { Name = "B", Amount = 600 };
Item T3 = new Item() { Name = "C", Amount = 100 };
Item T4 = new Item() { Name = "D", Amount = 150 };
Item T5 = new Item() { Name = "E", Amount = 200 };
 
listItem.Add(T1);
listItem.Add(T2);
listItem.Add(T3);
listItem.Add(T4);
listItem.Add(T5);
 
Decimal D = listItem.Sum(P=>P.Amount);
// sum of Amount
Conditional Sum
Assume that you want to get the summation of Amount lager than 100
Decimal D = listItem.Where(P=>P.Amount>100).Sum(P=>P.Amount);
List.Sum()
This will return the summation of the list.
List<int> intList = new List<int>();
 
intList.Add(2);
intList.Add(3);
intList.Add(4);
 
int sum = intList.Sum();
// sum of Amount
Post a Comment