LINQ DynamicLibrary:如何从IQueryable中提取计数和列表

时间:2011-03-03 15:27:07

标签: c# linq linq-to-objects dynamic-linq

我已经开始尝试使用LINQ DynamicLibrary了。我试图用一些或只有一个动态LINQ查询替换一堆LINQ语句。我现有的静态查询如下:

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();
}

如你所见,我的工作单位是ServiceItem。 这一切都很好,并为我提供了一个按Region分组的结果集。使用DynamicLibrary,我的尝试是能够按任何有效的动态字段进行分组(我将单独处理任何验证)。所以,我尝试使用DynamicLibrary编写相同的查询,但不是很成功。这是新方法,当然不能编译:

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();
}

我无法从分组中提取CountList。我该怎么做呢?我花了相当多的时间寻找解决方案。如果可能的话,我希望能够避免使用Reflection。我在以下链接的前面有一些指示,但它对我的实际问题没有帮助。提前感谢您的帮助。

System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

2 个答案:

答案 0 :(得分:2)

对于计数,可以写成如下:

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
}

对于列表 - 您可能需要将自定义实现添加到DynamicLibrary ... 看看它是如何为Contains()方法here

完成的

答案 1 :(得分:0)

解决方案是使用我的产品AdaptiveLINQ提供的.QueryByCube LINQ扩展方法。

免责声明:我是AdaptiveLINQ开发人员

相关问题