如何使用LINQ将给定数据转换为IEnumerable对象 [英] How to convert given data into IEnumerable object using LINQ
问题描述
我有下面的代码在c#4,我试图使用linq进行排序,分组。
I have below code in c# 4, where I am trying to use linq for ordering, grouping.
IList<Component> components = Component.OrganizationalItem.OrganizationalItem.Components(true);
IEnumerable<Component> baggage = components.Where(x => x.IsBasedOnSchema(Constants.Schemas.BaggageAllowance.ToString()))
.OrderBy(x => x.ComponentValue("name").StringValue("Code"))
.GroupBy(x => x.ComponentValue("name").StringValue("Code"));
在上面的示例中,当我尝试使用 GroupBy
它给错误,请看下面:
In above sample when I am trying to use GroupBy
it is giving error, please see below:
错误1无法隐式转换类型'System.Collections.Generic.IEnumerable>'为'System.Collections .Generic.IEnumerable'。显示转换(您缺少转换吗?)
Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
推荐答案
GroupBy
将是 IGrouping< string,Component>
- 它是一个组组件序列,而不是一个组件序列。这是整个分组。所以这应该很好:
The result of GroupBy
will be an IGrouping<string, Component>
- it's a sequence of groups of components, rather than one sequence of components. That's the whole point of grouping. So this should be fine:
IEnumerable<IGrouping<string, Component>> baggage = ... query as before ...;
或仅使用隐式类型:
var baggage = ...;
您可以遍历这些组:
foreach (var group in baggage)
{
Console.WriteLine("Key: {0}", group.Key);
foreach (var component in group)
{
...
}
}
这篇关于如何使用LINQ将给定数据转换为IEnumerable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!