LINQ group by query使用反射属性名称

NZJ*_*mes 4 c# linq reflection

我想用特定对象的公共属性填充下拉列表,我做得很好.但是现在当用户从下拉列表中选择值时,我希望它按该列对数据库表结果进行分组.我尝试过使用LINQ,但我只能弄清楚如何通过实例变量属性显式分组,而不是通过反射属性.这是我的方法 - 传入的参数是属性的字符串名称.例如,如果用户想要按Customer.Country分组,它将是"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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Est*_*din 15

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

_customerInterface.CustomerInterface.GetAllCustomers()
     .GroupBy(c => c.GetType().GetProperty(category).GetValue(c, null))
Run Code Online (Sandbox Code Playgroud)

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

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