views:

63

answers:

3

I have some code that creates a 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?

+1  A: 

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 ) );
Winston Smith
That would return an `IEnumerable<IEnumerable<IGrouping<TWhatever, Device>>>`
Thomas Levesque
@Thomas Should have used `SelectMany` of course, answer updated. Thanks.
Winston Smith
+2  A: 

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

Grozz
+1  A: 

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;
David B