I am playing about with the IQueryProvider.Execute command and am passing in an expression which is part of my expression tree project. This command gives me back an object which can be either an OrderedEnumerable or a GroupedEnumerable depending on the original expression. A GroupBy expression creates the GroupedEnumerable object. The following code also creates a GroupedEnumerable object which will show you an example of the problem I am having.
List<int> numbers = new List<int> { 1, 7, 16, 23, 41, 66 };
object grouped = numbers.GroupBy(n => n % 2 == 0);
When “grouped” is an object (of GroupedEnumerable) I cannot cast it to any other type that will allow me to call “GetEnumerator” on it. I am also unable to cast it to anything that will allow me to use it with a “foreach” command for example. If I change the code to use a “var” (as shown below), grouped is now of type OrderedEnumerable. I can get the enumerator and use it in a foreach command.
List<int> numbers = new List<int> { 1, 7, 16, 23, 41, 66 };
var grouped = numbers.GroupBy(n => n % 2 == 0);
Going back to my expression tree project, the IQueryProvider.Execute command returns an object but I need to be able to cast the object to an OrderedEnumerable when the object is a GroupedEnumerable. All the casts I have tried show an error along the lines of “Unable to cast object of type 'System.Linq.GroupedEnumerable`3 to type .....”. Anyone able to tell me how to cast the object to something more useful?