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
IEnumerable
of groupings. IEnumerable<IGrouping<AnimalType, Animal>>
but I cant see how to get that type.orderedAnimalTypes.SelectMany
(
animalType => GetAnimals(animalType),
(animalType, animal) => new { animalType, animal }
)
.
GroupBy(item => item.animalType, item => item.animal);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With