How to convert given data into IEnumerable object using LINQ

时光总嘲笑我的痴心妄想 提交于 2020-01-05 07:00:48

问题


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

In above sample when I am trying to use GroupBy it is giving error, please see below:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)


回答1:


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 ...;

Or just use implicit typing:

var baggage = ...;

You can then iterate over the groups:

foreach (var group in baggage)
{
    Console.WriteLine("Key: {0}", group.Key);
    foreach (var component in group)
    {
        ...
    }
}


来源:https://stackoverflow.com/questions/16075624/how-to-convert-given-data-into-ienumerable-object-using-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!