Search code examples
c#castingienumerableigrouping

C# How can I Cast/Convert a IEnumerable<IGrouping<object, object>> to another type?


So, I am trying to cast the following variable:

IEnumerable<IGrouping<object, object>> GroupedValues;

To this:

IEnumerable<IGrouping<int, int>> GroupedValues;

I have tried using Cast and also

Convert.ChangeType(GroupedValues, typeof(int));

but if It doesn't seem like a valid conversion if I compare it with a IEnumerable<IGrouping<int, int>> variable;


Solution

  • You can't cast it because it's not contravariant- you could reproject it (assuming that all keys and values are castable to int):

    var q = GroupedValues.SelectMany(g => g.Select (gv => new {Key = (int)g.Key, Item = (int)gv}))
                         .GroupBy (g => g.Key, g => g.Item);
    

    Or change the initial query to case the key and items.