Tutorial :Create IGrouping from an already grouped datastructure



Question:

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.


Solution:1

orderedAnimalTypes.SelectMany  (      animalType => GetAnimals(animalType),       (animalType, animal) => new { animalType, animal }  )  .  GroupBy(item => item.animalType, item => item.animal);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »