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 是一个字符串,而 Category 是一个 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)
};
在这两种情况下我都得到:
无法隐式转换类型....存在显式转换(您是否缺少强制转换)
我该如何强制转换?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,您必须使用
var
因为您有一个匿名类型。这种情况实际上就是为什么有必要将var
添加到语言中的原因。如果您想编写显式类型而不是 var,那么您必须选择一个必须在某处定义的具体类。那么您的代码可能如下所示:我怀疑上述查询不正确。您执行分组,但随后仅使用
grouped.Key
。In this case you have to use
var
because you have an anonymous type. This situation is in fact why it was necessary to addvar
to the language. If you want to write an explicit type instead ofvar
then you have to select a concrete class which must be defined somewhere. Then your code can look like this:I suspect though that the above query is not correct. You perform a grouping but then you only use
grouped.Key
.您需要为此定义一个具体类型。
select new
语句将返回匿名类型,因此您将获得匿名类型的可枚举值。如果您想要其他东西,您可以定义一个类,然后使用select new MyClass
代替,为您提供 MyClass 的 IEnumerable。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 useselect new MyClass
instead, giving you an IEnumerable of MyClass.您可以编写如下查询:
在这种情况下,类型为
You might write a query like this:
In that case, the type is