我需要动态地使用linq对列进行分组,即用户将在运行时选择表和列。
例如:上表有Territory,
State,BankName,
假设用户已选择这些列进行分组(区域,银行名称)
如何使用linq来做到这一点?
答案 0 :(得分:1)
您可能想要使用System.Linq.Dynamic
var fields = new List<string>() { "Territory", "Bank Name"};
var qfields = string.Join(", ", fields.Select(x => "it[\"" + x + "\"] as " + x));
var q = dt
.AsEnumerable()
.AsQueryable()
.GroupBy("new(" + qfields + ")", "it")
.Select("new (it as Data)");
foreach (dynamic d in q)
{
foreach (var row in d.Data)
{
// Do your work here, using d.Territory
}
}
查看此帖子Split a Datatable into multiple Datatables based on a list of column names