Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create IGrouping from an already grouped datastructure

Tags:

I've got a LINQ problem thats got me a little stumped. I can see plenty of alternative ways to find a solution but would like to try to solve the problem cos its bugging me!

public enum AnimalType {
    Cat,
    Dog,
    Rodent
}

var orderedAnimalTypes = new [] { AnimalType.Rodent, AnimalType.Cat };

I have a function GetAnimals(AnimalType type) that returns all the animals of a given type. I want to take orderedAnimalTypes and lookup all the animals of that type to create an ordered list of groups.

I want to end up with an object of type IEnumerable<IGrouping<AnimalType, Animal>>. That is a list of groupings where the Key is of type AnimalType and the enumeration of the grouping is of type Animal.

So what i want to do is this (after projecting the orderedAnimalTypes list into an IEnumerable of groups.

foreach (var group in groups) {
    AnimalType animalType = group.Key;
    IEnumerable<Animal> animals = group.ToArray();
}

I just cant seem to do this with any LINQ constructs. I'm thinking i may need to make my own implementation of IGrouping to do it but I'm not sure.

Alternatives

  • I could very easily do what I'm wanting with a dictionary, but then it wouldn't be ordered. That why I'm trying to get an IEnumerable of groupings.
  • I could also use an anonymous type, but i want to assign the result to an MVC model and that nees to be strongly typed.. The type i want is IEnumerable<IGrouping<AnimalType, Animal>> but I cant see how to get that type.
like image 724
Simon_Weaver Avatar asked Oct 17 '09 05:10

Simon_Weaver


1 Answers

orderedAnimalTypes.SelectMany
(
    animalType => GetAnimals(animalType), 
    (animalType, animal) => new { animalType, animal }
)
.
GroupBy(item => item.animalType, item => item.animal);
like image 88
Petr Behenský Avatar answered Oct 05 '22 12:10

Petr Behenský