我需要将以下 LINQ 查询转换为根据用户输入接受多个分组列的动态 LINQ。基本上我有一堆应用分组的下拉列表,我不想枚举分组的每个组合。如果动态 LINQ 失败,我可能不得不手动构建 SQL 查询,而没有人愿意这样做。
var grouping = ( from entry in ObjectContext.OmniturePageModules
where entry.StartOfWeek >= startDate && entry.StartOfWeek <= endDate &&
( section == "Total" || section == "All" || entry.Section == section ) &&
( page == "Total" || page == "All" || entry.Page == page ) &&
( module == "Total" || module == "All" || entry.Module == module )
group entry by new
{
entry.Page, // I want to be able to tell this anonymous type
entry.Module, // which columns to group by
entry.StartOfWeek // at runtime
}
into entryGroup
select new
{
SeriesName = section + ":" + entryGroup.Key.Page + ":" + entryGroup.Key.Module,
Week = entryGroup.Key.StartOfWeek,
Clicks = entryGroup.Sum( p => p.Clicks )
} );
我不知道如何做到这一点,因为动态 LINQ 在“你好世界!”之外完全没有记录。select/where/orderby 案例。我只是无法弄清楚语法。
就像是:(?)
var grouping = ObjectContext.OmniturePageModules.Where(entry => entry.StartOfWeek >= startDate && entry.StartOfWeek <= endDate &&
( section == "Total" || section == "All" || entry.Section == section ) &&
( page == "Total" || page == "All" || entry.Page == page ) &&
( module == "Total" || module == "All" || entry.Module == module ))
.GroupBy("new (StartOfWeek,Page,Module)", "it")
.Select("new (Sum(Clicks) as Clicks, SeriesName = section + key.Page + Key.Module, Week = it.Key.StartOfWeek)");
我在 System.Linq.Dynamic 中使用 DynamicQueryable 类。请参阅:http ://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
跟进:Enigmativity 的解决方案主要工作。出于某种原因,它不想按日期时间“StartOfWeek”列进行分组——解决方法只是进行二次分组:
var entries = ( from entry in ObjectContext.OmniturePageModules
where entry.StartOfWeek >= startDate
&& entry.StartOfWeek <= endDate
&& ( section == "Total" || section == "All" || entry.Section == section )
&& ( page == "Total" || page == "All" || entry.Page == page )
&& ( module == "Total" || module == "All" || entry.Module == module )
select entry ).ToArray(); // Force query execution
var grouping = from entry in entries
let grouper = new EntryGrouper( entry, section, page, module )
group entry by grouper into entryGroup
select new
{
entryGroup.Key.SeriesName,
entryGroup.Key.Date,
Clicks = entryGroup.Sum( p => p.Clicks ),
};
var grouping2 = (from groups in grouping
group groups by new {groups.SeriesName, groups.Date } into entryGroup
select new
{
entryGroup.Key.SeriesName,
entryGroup.Key.Date,
Clicks = entryGroup.Sum( p => p.Clicks ),
} );
但这似乎会严重降低性能... =/