views:

221

answers:

3

I have the following query:

var groupCats =
            from g in groups
            group g by g.Value into grouped
            select new
            {
                GroupCategory = grouped.Key,
                Categories = GetCategories(grouped.Key, child)
            };

This works fine. In the anonymous type returned GroupCategory is a string, and Categories are an Enumerable - what is the proper way to declare this instead of using 'var'?

I tried:

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

and

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

In both instances I get:

Cannot implicity convert type....An explicit conversion exists (are you missing a cast)

How do I cast this?

+2  A: 

In this case you have to use var because you have an anonymous type. This situation is in fact why it was necessary to add var to the language. If you want to write an explicit type instead of var then you have to select a concrete class which must be defined somewhere. Then your code can look like this:

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

I suspect though that the above query is not correct. You perform a grouping but then you only use grouped.Key.

Mark Byers
+2  A: 

You would need to define a concrete type for this. The select new statement is going to return an anonymous type, so you're going to have an enumerable of the anonymous type. If you want something else, you would define a class and then use select new MyClass instead, giving you an IEnumerable of MyClass.

Anthony Pegram
A: 

You might write a query like this:

from g in groups 
group g by g.Value

In that case, the type is

IEnumerable<IGrouping<KeyType, GType>> groupCats = 
David B
So the type would be: IEnumerable<IGrouping<string,IEnumerable<string>>> ?which still gives me the invalid cast exception. So I still need a concrete class implementation as indicated in the other answers?
FiveTools
No, the type would be IEnumerable<CompilerNamedType>, but you can't use CompilerNamedType before the compiler names it, so you have to use var.
David B