LINQ Dynamic Group by inquiry

c# dynamic-linq linq visual-studio

Question

I am using Dyanmic LINQ from the VS2010 code samples as I am trying to create a LINQ groupby expression. I want to allow the user the possibility to select at runtime the properties to group on/by as well as the period of grouping (year, quarter, month). Because of this, I decided to go for Dynamic LINQ.

Here's a sample of my data:

ID| Income | OrDate |
1 | 900000 | 1-1-2000 |
2 | 180000 | 1-9-2000 |
3 | 300000 | 3-2-2002 |
4 | 100000 | 2-7-2003 |

and the expression I build looks like:

dataSource.GroupBy("new (OrDate.Year as Year, OrDate as Month)", "Income").Select("new (Key.Year, Key.Month, Sum(Value) as Income)");

This works well ONLY I know the exact type of the list; for example: List<Product> or List<Order>. My problem is that the dataSource type at compile time is a List<object>. Because of this, whenever I fill the list with Orders or Products, I get an exception:

No generic method 'GroupBy' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

Can anyone tell me how can this be avoided and still keep the source list as a List<object>?

1
3
3/20/2011 6:52:55 PM

Popular Answer

Try this -

For group by in LinQ

var x = t.GroupBy(gp => gp.Name).OrderBy(group => group.Key).Select(group => Tuple.Create(group.Key, group.Count()));

Please find

https://dotnetfiddle.net/WPqzhJ

0
9/1/2015 12:45:08 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow