How to retrieve count and list from IQueryable with LINQ DynamicLibrary

c# dynamic-linq linq linq-to-objects

Question

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>)

1
4
5/23/2017 12:04:11 PM

Popular Answer

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

2
3/9/2011 11:06:22 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