IGrouping和Linq中
问题描述:
铸造我有以下查询:IGrouping和Linq中
var groupCats =
from g in groups
group g by g.Value into grouped
select new
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
这工作得很好。在返回的匿名类型中,GroupCategory是一个字符串,Categories是一个Enumerable - 声明这个而不是使用'var'的正确方法是什么?
我想:
和
IGrouping<string,Enumerable<string>> groupCats =
from g in groups
group g by g.Value into grouped
select new
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
在这两种情况下,我得到:
不能含蓄转化类型....一个显式转换存在(是否缺少强制)
我该如何施展?
答
在这种情况下,您必须使用var
,因为您有一个匿名类型。这种情况实际上是为什么有必要在语言中添加var
。如果你想写一个明确的类型而不是var
那么你必须选择一个具体的类,它必须在某个地方定义。然后你的代码可以看起来像这样:
IEnumerable<MyClass> groupCats =
from g in groups
group g by g.Value into grouped
select new MyClass
{
GroupCategory = grouped.Key,
Categories = GetCategories(grouped.Key, child)
};
我怀疑虽然上述查询是不正确的。你执行一个分组,但你只能使用grouped.Key
。
答
您需要为此定义一个具体类型。 select new
声明将返回一个匿名类型,因此您将拥有一个匿名类型的枚举。如果你想要别的东西,你可以定义一个类,然后改用select new MyClass
,给你一个IEnumerable的MyClass。
答
你可能会写这样的查询:
from g in groups
group g by g.Value
在这种情况下,该类型是
IEnumerable<IGrouping<KeyType, GType>> groupCats =
所以类型是:IEnumerable的 >>? 这仍然给我无效的转换异常。所以我仍然需要一个具体的类实现,如其他答案中所示? –
FiveTools
2010-05-07 12:21:49
不,该类型为IEnumerable,但在编译器命名之前不能使用CompilerNamedType,因此必须使用var。 –
2010-05-07 13:49:46