Kia*_*ada 3 .net c# asp.net-mvc-3
我想知道如何创建一个可重用的方法,根据方法参数创建选择列表?我在想下面的事情:
public IEnumerable<SelectListItem> CreateSelectList(IList<T> entities, T value, T text)
{
return entities
.Select(x => new SelectListItem
{
Value = x.value.ToString(),
Text = x.text.ToString()
});
}
Run Code Online (Sandbox Code Playgroud)
我想我有点倒退了.我不确定如何调用这样的方法,当我用类别的IList为第一个参数调用它时,编译器抱怨它不能将类型类型分配给类型T?另外,我如何将方法参数插入lambda?任何帮助赞赏!
代码我试图用来调用它(这是错误的,但你明白了)
viewModel.Categories = _formServices.CreateSelectList(categories, Id, Name);
Run Code Online (Sandbox Code Playgroud)
代码我试图使更通用和可重用:
viewModel.Categories = categories
.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
Run Code Online (Sandbox Code Playgroud)
编辑答案
感谢@Pavel Backshy的工作回答.我想编辑一个扩展,我做了他的回答,以防它帮助任何人!扩展只是在混合中添加.Where子句:
public IEnumerable<SelectListItem> CreateSelectListWhere<T>(IList<T> entities, Func<T, bool> whereClause, Func<T, object> funcToGetValue, Func<T, object> funcToGetText)
{
return entities
.Where(whereClause)
.Select(x => new SelectListItem
{
Value = funcToGetValue(x).ToString(),
Text = funcToGetText(x).ToString()
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Reflection来定义它,以便按名称获取属性值,但我认为使用Func更加优雅和灵活.将您的方法更改为:
public IEnumerable<SelectListItem> CreateSelectList<T>(IList<T> entities, Func<T, object> funcToGetValue, Func<T, object> funcToGetText)
{
return entities
.Select(x => new SelectListItem
{
Value = funcToGetValue(x).ToString(),
Text = funcToGetText(x).ToString()
});
}
Run Code Online (Sandbox Code Playgroud)
然后您可以通过这种方式使用它:
viewModel.Categories = _formServices.CreateSelectList(categories, x => x.Id, x => x.Name);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3396 次 |
最近记录: |