Reputation: 159
I have started experimenting a bit with the LINQ DynamicLibrary. I am trying to replace a bunch of LINQ statements with a few or just one Dynamic LINQ query. My existing static query is as follows:
private List<TicketChartData> GenerateImpl(IList<ServiceItem> myList)
{
var output = from ticket in myList
group ticket by ticket.Region into grouped
orderby grouped.Count() descending
select new TicketChartData(grouped.Key, grouped.Count(), grouped.ToList());
return output.ToList();
}
As you see, my unit of work is ServiceItem
.
This works all fine and gets me a result set grouped by Region
. Using DynamicLibrary my attempt is to be able to group by any valid dynamic field (I will handle any validations separately). So, I tried writing the same query using DynamicLibrary, but am not very successful. Here is the new method which of course doesn't compile:
private List<TicketChartData> GenerateImpl(IList<ServiceItem> myList, string field)
{
IQueryable<ServiceItem> queryableList = myList.AsQueryable<ServiceItem>();
IQueryable groupedList = queryableList.GroupBy(field,"it").
OrderBy("Key descending").
Select("new (Key as Key)"); // Not what i need
return output.ToList();
}
I have been unable to extract neither the Count
nor the List
from the grouping. How do I do this? I have spent considerable amount of time looking for a solution. If possible I want to be able to avoid using Reflection. I have had some pointers in this front at the following link, but it doesn't help my actual problem. Thanks in advance for any help.
System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)
Upvotes: 4
Views: 1722
Reputation: 1288
A solution is to use the .QueryByCube
LINQ extension method provided by my product AdaptiveLINQ.
Disclaimer: I'm the AdaptiveLINQ developer
Upvotes: 0
Reputation: 2804
For Count it can be written as following:
private List GenerateImpl(IList myList, string field)
{
IQueryable queryableList = myList.AsQueryable();
IQueryable groupedList = queryableList.GroupBy(field,"it").
OrderBy("Key descending").
Select("new (Key as Key, Count() as Count)");
// Note: IQueryable doesn't have ToList() implementation - only IEnumerable
return output.ToList(); // will not work
}
For List - possible you'll need to add your custom implementation to DynamicLibrary... See how it was done for Contains() method here
Upvotes: 2