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

发布于 2024-08-08 05:57:54 字数 1124 浏览 9 评论 0 原文

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

public enum AnimalType {
    Cat,
    Dog,
    Rodent
}

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

我有一个函数GetAnimals(AnimalType type),它返回给定类型的所有动物。我想采用 orderedAnimalTypes 并查找该类型的所有动物以创建组的有序列表。

我希望最终得到一个 IEnumerable> 类型的对象。 这是一个分组列表,其中 Key 的类型为 AnimalType,分组的枚举的类型为 Animal。

所以我想做的是这样的(在将 orderedAnimalTypes 列表投影到 IEnumerable 组之后。

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

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

替代方案

  • 我可以很容易地用字典做我想做的事情,但这样就不会被排序。 。 那 为什么我试图获取分组的 IEnumerable
  • 我也可以使用匿名类型,但我想将结果分配给 MVC 模型,并且需要强类型化。我想要的类型是 IEnumerable>但我不知道如何获得这种类型。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倦话 2024-08-15 05:57:54
orderedAnimalTypes.SelectMany
(
    animalType => GetAnimals(animalType), 
    (animalType, animal) => new { animalType, animal }
)
.
GroupBy(item => item.animalType, item => item.animal);
orderedAnimalTypes.SelectMany
(
    animalType => GetAnimals(animalType), 
    (animalType, animal) => new { animalType, animal }
)
.
GroupBy(item => item.animalType, item => item.animal);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文