简体   繁体   中英

Dynamic LINQ GroupBy 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> ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM