我有一个 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.
发布评论
评论(1)