Linq query

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

I have a collection with some fields we can just assume that
we have the follwing two fields
Parameter Value
cc 4
cc 4
cc 5
cc 5
cc 5
cc 6
cc 40
cc 40
cc 40
bc 7
bc 7

In the quesy I want to group by on Parameter = cc
so I want to get the number of rows where each unique number occur for
parameter =cc
In this example I want the following output
cc 4 2 // Here I know that I have two rows with value 4
cc 5 3 // Here I know that I have 3 rows with value 5
cc 6 1 // Here I know that I have 1 row with value 6
cc 40 3 // Here I know that I have 3 rows with value 40

//Tony
 
Say the two properties are Foo and Bar; then you have:

var qry = from item in data
group item by new { item.Foo, item.Bar } into grp
select new {grp.Key.Foo, grp.Key.Bar,
Count = grp.Count()};
foreach (var row in qry)
{
Console.WriteLine("{0}\t{1}\t{2}",
row.Foo, row.Bar, row.Count);
}

(feel free to add an order too)

Marc
[C# MVP]
 
Sorry - I misread; since you only want "cc" rows, you need a "where",
and only a simple (not composite) group:

var qry = from item in data
where item.Foo == "cc"
group item by item.Bar into grp
select new {Bar = grp.Key, Count = grp.Count()};
foreach (var row in qry)
{
Console.WriteLine("{0}\t{1}", row.Bar, row.Count);
}

Marc
[C# MVP]
 
Back
Top