c# - 将 IEnumerable<T> 转换为 List<SelectListItem> 的 Lambda 扩展方法

标签 c# linq generics

我需要一种方法来创建 IEnumerable 的扩展方法,以允许我返回 SelectListItem 的列表。

例如

    public class Role
    {
        public string Name {get;set;}
        public string RoleUID {get;set;}
    }
    IEnumerable<Role> Roles = .../*Get Roles From Database*/
    var selectItemList = Roles.ToSelectItemList(p => p.RoleUID,r => r.Name);

这会给我一个 SelectItemList,名称是显示,RoleUID 是值。

重要我希望它是通用的,这样我就可以使用一个对象的任意两个属性来创建它,而不仅仅是角色类型的对象。

我该怎么做?

我想像下面这样的东西

 public static List<SelectItemList> ToSelectItemList<T,V,K>(this IEnumerable<T>,Func<T,V,K> k)

或者什么的,我显然知道那是不正确的。

最佳答案

为什么不结合现有的 SelectToList 方法?

var selectItemList = Roles
  .Select(p => new SelectListItem { Value = p.RoleUID, Text = p.Name })
  .ToList();

如果您想专门将它放入一个方法中,那么您可以将 ToSelectListItem 定义为这两种方法的组合。

public static List<SelectListItem> ToSelectListItem<T>(
  this IEnumerable<T> enumerable,
  Func<T, string> getText,
  Func<T, string> getValue) {

  return enumerable
    .Select(x => new SelectListItem { Text = getText(x), Value = getValue(x) })
    .ToList();
}

关于c# - 将 IEnumerable<T> 转换为 List<SelectListItem> 的 Lambda 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7562339/

相关文章:

c# - 运算符 '==' 不能应用于类型 'method group' 和 'string' 的操作数

reactjs - Typescript 中抽象泛型 Container 类子类的装饰器

c# - Blazor 相当于 WPF ShowDialog()?

c# - 在打印机之间传输打印作业

c# - 用空格替换所有非单词字符

c# - 为什么 Visual Studio 2010 不允许在 linq 查询中使用 "is null"而 VS2017 允许?

c# - 如何计算 Entity Framework 中的非原始对象列表?

c# - 带有 Id 的通用类 C#

c# - 确定字段是否使用通用参数

c# - 如何枚举给定根对象的所有可到达对象?