views:

153

answers:

2

Given a set

Paris New York London New York Paris Paris

I'm trying to do a LINQ query that will return a grouping of the Paris, New York, and London with their respective counts.

I've been able to do a GroupBy that returns a group containing only the Paris/New York/London in each Grouping.

Sounds relatively simple, but I can't get it to work?

Edit: It's not a homework problem.

A: 

Use .Count() on the groupings.

Yuriy Faktorovich
+8  A: 

CODE

String[] input = new [] { "Paris", "New York", "London",
                          "New York", "Paris", "Paris" };

var groups = input
    .GroupBy(city => city)
    .Select(group => new { City = group.Key, Count = group.Count() });

foreach(var group in groups)
{
    Console.WriteLine("{0} occurs {1} time(s).", group.City, group.Count);
}

OUTPUT

Paris occurs 3 time(s).
New York occurs 2 time(s).
London occurs 1 time(s).
Daniel Brückner
I didn't give full answer because it sounded like a homework question. Also you can shorten it by using a different overload of the GroupBy method.
Yuriy Faktorovich