Linq的IGrouping和Casting

时间:2010-05-06 18:42:03

标签: linq casting grouping

我有以下查询:

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,string> groupCats =
            from g in groups
            group g by g.Value into grouped
            select new
            {
                GroupCategory = grouped.Key,
                Categories = GetCategories(grouped.Key, child)
            };

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)
            };

在这两种情况下,我得到:

不能隐含转换类型....存在显式转换(您是否错过了转换)

我该如何投这个?

3 个答案:

答案 0 :(得分:3)

在这种情况下,您必须使用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

答案 1 :(得分:3)

您需要为此定义具体类型。 select new语句将返回匿名类型,因此您将拥有匿名类型的可枚举。如果你想要别的东西,你可以定义一个类,然后使用select new MyClass代替,给你一个IEnumerable的MyClass。

答案 2 :(得分:0)

您可以编写如下查询:

from g in groups 
group g by g.Value

在这种情况下,类型是

IEnumerable<IGrouping<KeyType, GType>> groupCats =