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

It works great. In the returned anonymous type, GroupCategory is a string and Categories is 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 cases, I get:

Impossible to convert type implicity .... Explicit conversion exists (you are missing a cast)

How to do it?

+4
source share
3 answers

In this case, you should use var because you have an anonymous type. In this situation, you really need to add var to the language. If you want to write an explicit type instead of var , then you need to select a specific class that needs to be defined somewhere. Then your code might 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 the above request is incorrect. You do the grouping, but then only use grouped.Key .

+3
source

To do this, you need to define a specific type. The select new operator returns an anonymous type, so you will have an enumeration of an anonymous type. If you want something else, you must define a class, and then use select new MyClass instead, giving you an IEnumerable MyClass.

+3
source

You can write a query like this:

 from g in groups group g by g.Value 

In this case, the type

 IEnumerable<IGrouping<KeyType, GType>> groupCats = 
0
source

Source: https://habr.com/ru/post/1309042/


All Articles