views:

74

answers:

3

I have a IEnumerable collection of Car objects

A Car has a property: Year

Using LINQ, I want to find where there are > 1 cars with the same year and return that list.

I would expect it to have to return an array of lists because if the collection is:

Car 1: Year 2010
Car 2: Year 2010
Car 3: Year 2009
Car 4: Year 2009
Car 5: Year 2010
Car 6: Year 2008

I would expect one list of 3 for 2010 and one list of 2 for 2009

is this possible ?

+1  A: 

Try the following

List<Car> list = null;
IEnumerable<List<Car>> ret = 
    from it in list
    group it by it.Year into g
    where g.Count() > 1 
    select g.ToList();
JaredPar
+3  A: 

You can do this with group by. See hooked on linq for more samples

var result = from car in cars
             group car by car.year into g
             where g.Count() > 1
             select g

now result is an IEnumerable<IGrouping<int, Car>>, meaning you can do this:

foreach(var g in result)
{
    int year = g.Key;
    foreach(var car in g)
    {
        // list the cars
    }
}
Sander Rijken
No critism of you example but sometimes I wish Linq had an AtLeast(int count) method (I ended up writing one). I know Group probably returns an ICollection<T> under the covers which is optimised in Count() but it still worries me everytime I write or see something like this.
Bear Monkey
A: 
IEnumerable<List<Car>> carsGroupedByYear = 
    cars.GroupBy(c => c.Year) /* Groups the cars by year */
        .Where(g => g.Count() > 1) /* Only takes groups with > 1 element */
        .Select(g => g.ToList()); /* Selects each group as a List<Car> */
Joviee
That's exactly the same answer as JaredPar's
Sander Rijken
Fluent syntax needed some love.
Joviee