IGrouping and Casting in Linq
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> gr开发者_JAVA百科oupCats =
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?
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
.
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.
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 =
精彩评论