I'd suggest to download it:
101 LINQ Samples in C#[
^]. There you'll find what you're looking for ;)
For further information, please see:
How to: Write LINQ Queries in C#[
^]
How to: Count, Sum, or Average Data by Using LINQ (Visual Basic)[
^] - this is what you need ;)
Aggregate Queries[
^]
I'm using
LinqPad[
^] quite often. It might help you to write proper query.
Example:
void Main()
{
List<Human> humans = new List<Human> {
new Human("Andrew", 25),
new Human("Marta", 24),
new Human("Roberto", 25),
new Human("Zenobia", 21),
new Human("Utopia", 25),
new Human("Ramdion", 20),
new Human("Ewa", 25),
new Human("Jeremy", 24),
new Human("Isabell", 25),
new Human("Isaura", 23),
new Human("Gregor", 25),
new Human("Evan", 23),
new Human("Natasha", 25),
new Human("Trevor", 21)};
var qry = from hum in humans
group hum by hum.Age into grp
select new{ag=grp.Key, co=grp.Count()};
foreach (var rec in qry)
{
Console.WriteLine("Age={0}; Count={1}", rec.ag, rec.co);
}
}
public class Human
{
private string sName = string.Empty;
private int iAge = 0;
public Human(string aName, int aAge)
{
sName=aName;
iAge=aAge;
}
public string Name
{
get{return sName;}
set{sName = value;}
}
public int Age
{
get{return iAge;}
set{iAge = value;}
}
}
Result:
Age=25; Count=7
Age=24; Count=2
Age=21; Count=2
Age=20; Count=1
Age=23; Count=2
As you can see, you're able to group data depending on your needs.