Retrocoder
Retrocoder

Reputation: 4713

Casting a list of lists to IGrouping?

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?

Upvotes: 1

Views: 2282

Answers (3)

Amy B
Amy B

Reputation: 110111

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;

Upvotes: 1

Grozz
Grozz

Reputation: 8425

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

Upvotes: 2

Winston Smith
Winston Smith

Reputation: 21882

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

Upvotes: 1

Related Questions