Create IGrouping from an already grouped data structure

I have a LINQ problem that puzzled me a bit. I can see many alternative ways to find a solution, but I would like to try to solve the problem because he was listening to me!

public enum AnimalType {
    Cat,
    Dog,
    Rodent
}

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

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

I want to get an object of type IEnumerable<IGrouping<AnimalType, Animal>>. This is a list of groups where it Keyhas a type AnimalType, and the group enumeration is of type Animal.

So I want to do this (after projecting the list orderedAnimalTypesinto IEnumerablegroups.

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

LINQ. , , , IGrouping, .

  • , , . IEnumerable .
  • , MVC, . , , IEnumerable<IGrouping<AnimalType, Animal>>, , .
+3
1
orderedAnimalTypes.SelectMany
(
    animalType => GetAnimals(animalType), 
    (animalType, animal) => new { animalType, animal }
)
.
GroupBy(item => item.animalType, item => item.animal);
+3

Source: https://habr.com/ru/post/1720336/


All Articles