LINQ 使用反射属性名称按查询分组

本文关键字:查询 反射 属性 LINQ | 更新日期: 2023-09-27 18:36:28

我想用特定对象的公共属性填充一个下拉列表,我已经做得很好了。但是现在当用户从下拉列表中选择值时,我希望它按该列对数据库表结果进行分组。我尝试过使用 LINQ,但我只能弄清楚如何按实例变量属性而不是反射属性显式分组。这是我的方法 - 传入的参数是属性的字符串名称。例如,如果用户想要按 Customer.Country 分组,它将是"国家",如果用户想要按 Customer.State 分组,它将是"State"。但是目前我已经硬编码为按"状态"分组,因为我无法弄清楚如何使用通过 LINQ 查询传入的字符串值

private void DisplayReportAction(string category)
{
    if (!string.IsNullOrEmpty(category))
    {
        SelectedCategory = category;
        _summaries.Clear();
        foreach (var custGroup in _customerInterface.CustomerInterface.GetAllCustomers().GroupBy(c => c.State)
            .Select(group => new
                                 {
                                     Category = group.Key,
                                     Count = group.Count()
                                 })
                                 .OrderBy(x => x.Category))
        {
            _summaries.Add(new CustomerReportSummaryViewModel(custGroup.Category, custGroup.Count));
        }
        ReportVisibility = Visibility.Visible;
    }
}

LINQ 使用反射属性名称按查询分组

如果使用 LINQ to Objects,则可以使用 Reflection,例如,您可以使用以下内容:

_customerInterface.CustomerInterface.GetAllCustomers()
     .GroupBy(c => c.GetType().GetProperty(category).GetValue(c, null))

如果您使用的是 Linq To Sql,那么另一种方法是使用动态查询,请查看此链接

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

您可以动态构建表达式:

    Expression<Func<Customer,T>> buildExpression<T>(string category)
    {
        //First build parameter of lambda ( 'c =>' part of expression)
        ParameterExpression param = Expression.Parameter(typeof(Customer), "c");
        //Then body of expression : ' => c.category'
        Expression<Func<Customer, T>> exp = Expression.Lambda<Func<Customer, T>>(Expression.Property(param, category), param);
        return exp;
    }

最后,打电话

_customerInterface.CustomerInterface.GetAllCustomers()
    .GroupBy(buildExpression(category))

编辑:好吧,抱歉,您仍然必须知道属性的类型才能将 T 类型参数提供给buildExpression函数

有一些方法可以做到这一点,例如使用 GetProperty(category).PropertyType 然后在GetType().GetMethod("buildExpression<>")上调用 MakeGenericMethod ,但这需要更多的工作。无论如何,您必须找到一种方法来从这种类型构建CustomerReportSummaryViewModel

我不知道您的用例,但是您可能所有类别属性都属于同一类型,因此您可以对其进行硬编码?

如果您有兴趣,并且找不到合适的方法,请告诉我我会尝试编写适当的解决方案。