【发布时间】:2018-08-07 17:29:41
【问题描述】:
我有一个以这种格式存储的排序列表:
public class ReportSort
{
public ListSortDirection SortDirection { get; set; }
public string Member { get; set; }
}
我需要把它变成Action<DataSourceSortDescriptorFactory<TModel>>类型的lambda表达式
所以假设我有以下报告排序集合:
new ReportSort(ListSortDirection.Ascending, "LastName"),
new ReportSort(ListSortDirection.Ascending, "FirstName"),
我需要将其转换为这样的语句才能像这样使用:
.Sort(sort => {
sort.Add("LastName").Ascending();
sort.Add("FirstName").Ascending();
})
排序方法签名是:
public virtual TDataSourceBuilder Sort(Action<DataSourceSortDescriptorFactory<TModel>> configurator)
所以我现在有一些方法:
public static Action<DataSourceSortDescriptorFactory<TModel>> ToGridSortsFromReportSorts<TModel>(List<ReportSort> sorts) where TModel : class
{
Action<DataSourceSortDescriptorFactory<TModel>> expression;
//stuff I don't know how to do
return expression;
}
...我不知道在这里做什么。
编辑:答案是:
var expression = new Action<DataSourceSortDescriptorFactory<TModel>>(x =>
{
foreach (var sort in sorts)
{
if (sort.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
{
x.Add(sort.Member).Ascending();
}
else
{
x.Add(sort.Member).Descending();
}
}
});
起初我在想我必须使用 Expression 类从头开始动态构建一个 lambda 表达式。幸运的是,情况并非如此。
【问题讨论】:
标签: c# linq lambda linq-to-objects kendo-ui-mvc