0

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;

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
Innat3
  • 3,561
  • 2
  • 11
  • 29
  • 2
    Does that `IGrouping` really contains `int`s? If so, why is that typed as object in first place? Where do you get that instance from? – Sriram Sakthivel Mar 03 '16 at 17:03

2 Answers2

3

You can do this

var result = GroupedValues.GroupBy(x => (int)x.Key, x => x.Cast<int>());

This will throw exception if any object is not int. so you can filter to get only integer items like this.

var result = GroupedValues.Where(x => x.Key is int && x.All(i => i is int)).GroupBy(x => (int)x.Key, x => x.Cast<int>());
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
2

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240