按字符串引用的属性动态分组

本文关键字:动态 属性 字符串 引用 | 更新日期: 2023-09-27 18:34:20

所以我有一个相对较大的数据集,我希望最终用户能够以某种方式进行自定义。

目前数据分组如下:

var versusHistories =
                from th in db.TeamHistories
                where th.TeamOneName.ToLower() == team.ToLower()
                group th by th.Date
                into grp1
                from grp2 in
                    (from th in grp1
                        group th by th.Event)
                group grp2 by grp1.Key;

如果我想允许用户指定group by子句,我将如何做到这一点?

例:

用户导航到 http://example.com/search?team=AbcTeam&grpBy1=TeamTwo&grpBy2=Date

然后,页面呈现以下代码:

var versusHistories =
                from th in db.TeamHistories
                where th.TeamOneName.ToLower() == team.ToLower()
                group th by th.TeamTwo
                into grp1
                from grp2 in
                    (from th in grp1
                        group th by th.Date)
                group grp2 by grp1.Key;

如何动态提供此功能,而无需对每种可能性进行硬编码?

按字符串引用的属性动态分组

使用方法语法,您可以执行以下操作:

var versusHistories =
            from th in db.TeamHistories
            where th.TeamOneName.ToLower() == team.ToLower()
if (condition)
{
    versusHistories = versusHistories.GroupBy(g => ..something..);
}
else if (anotherCondition)
{
    versusHistories = versusHistories.GroupBy(g => ..something else..);
}

我不确定纯查询语法是否/如何实现。

这样可以防止多次重复核心查询。

这不是一个完整的 anser,但您可以尝试使用反射并执行以下操作:

var listOfPropertiesToSortBy = new List<string>();
var versusHistories = from th in db.TeamHistories
                      where th.TeamOneName.ToLower() == team.ToLower();
foreach (var property in listOfPropertiesToSortBy ) {
       versusHistories = versusHistories.GroupBy(vh => typeof(TeamHistories).GetProperty(property).GetValue(vh));
}

这样做的问题是,每次迭代列表时,新的 OrderBy 语句都会覆盖最后一个语句。需要有办法说.然后通过第一个属性之后,但我知道 versusHistory = versus历史.thenBy(某物)无效。也许有人可以接受这个并扩展它来为你工作。希望这有帮助。