linq - 从已经分组的数据结构创建 IGrouping

标签 linq igrouping

我有一个 LINQ 问题,这让我有点困惑。我可以看到很多替代方法来找到解决方案,但我想尝试解决问题,因为它困扰着我!

public enum AnimalType {
    Cat,
    Dog,
    Rodent
}

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

我有一个功能 GetAnimals(AnimalType type)返回给定类型的所有动物。我要带orderedAnimalTypes并查找该类型的所有动物以创建一个有序的组列表。

我想最终得到一个类型为 IEnumerable<IGrouping<AnimalType, Animal>> 的对象.
这是一个分组列表,其中 Key类型为 AnimalType并且分组的枚举类型为 Animal。

所以我想做的是这个(在将 orderedAnimalTypes 列表投影到 IEnumerable 组之后。
foreach (var group in groups) {
    AnimalType animalType = group.Key;
    IEnumerable<Animal> animals = group.ToArray();
}

我似乎无法使用任何 LINQ 构造来做到这一点。我想我可能需要自己实现 IGrouping 才能做到这一点,但我不确定。

替代品
  • 我可以很容易地用字典做我想做的事,但它不会被订购。那
    为什么我想得到一个 IEnumerable的分组。
  • 我也可以使用匿名类型,但我想将结果分配给 MVC 模型并且需要强类型。我想要的类型是 IEnumerable<IGrouping<AnimalType, Animal>>但我看不出如何获得这种类型。
  • 最佳答案

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

    关于linq - 从已经分组的数据结构创建 IGrouping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1581525/

    相关文章:

    c# - 如何使用反射来调节多个属性以检查 LINQ .Where 语句中的相等性,具体取决于传递的类?

    c# - 如何在 LINQ 中询问 "Is there exactly one element satisfying condition"?

    LINQ 从 IGrouping 转换为 Lookup

    c# - 在 IGrouping 中获取 "Value"属性

    c# - 困难的层次排序

    linq - 定义导航属性时列表 vs IEnumerable vs IQueryable

    asp.net - CRM 2015 Linq Count() 查询 - 这是在枚举查询吗?