开发者

Casting a list of lists to IGrouping?

I have some code that creates a开发者_如何学C list of lists. The list is of this type:

 List<List<Device>> GroupedDeviceList = new List<List<Device>>();

But need to return the result in the following type:

 IEnumerable<IGrouping<object, Device>>

Is this possible via a cast etc or should I be using a different definition for my list of lists?


If I understood your intentions correctly, the answer is below:

    var result = GroupedDeviceList
        .SelectMany(lst => lst.GroupBy(device => (object)lst));

result is of type IEnumerable<IGrouping<object, Device>>, where object is a reference to your List<Device>.


IGrouping<T1,T2> is usually created via a LINQ GroupBy query.

How are you populating GroupedDeviceList? Are you doing this manually or converting it from the result of a .GroupBy?

You could perform the grouping again by doing something like this:

// IEnumerable<IGrouping<TWhatever, Device>>
var reGroupedList = 
    GroupedDeviceList
    .SelectMany( innerList => innerList.GroupBy( device => device.Whatever ) );


Presuming that the contents of each non-empty list should form a group...

IEnumerable<IGrouping<object, Device>> query =
  from list in lists
  from device in list
  group device by (object)list;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜