c# - 从 SelectListItem 列表中获取项目的值?

标签 c# list

我有以下类(class):

public static IEnumerable<SelectListItem> GetDatastore()
{
    return new[]
        {
            new SelectListItem { Value = "DEV", Text = "Development"  },
            new SelectListItem { Value = "DC1", Text = "Production" },
        };
}

我需要的是执行一个函数来返回数据存储名称。有点像

var abc = getDatastoreName("DEV"). 

我需要用 LINQ 来做这件事还是有一些简单的方法?我该如何编写此函数的代码?

最佳答案

public static string getDatastoreName(string name)
{
     var result = GetDatastore().SingleOrDefault(s => s.Value == name);
     if (result != null)
     {
         return result.Text;
     }
     throw /* some exception */
}

SelectListItemValue 属性通常是唯一的,因此我有SingleOrDefault()。如果不是这种情况,那么您可以切换到使用 FirstOrDefault()

关于c# - 从 SelectListItem 列表中获取项目的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6454634/

相关文章:

c# - 访问由另一个线程添加的字典项

c# - 字符串插值 : a bug in c# compiler?

c# - 保持 ASP.NET session 打开/事件

python - django - 将列表转换回查询集

arrays - 列出三维数组

Python添加列表作为字典中的键

javascript - 列表项中的jquery id?

python - 列表追加内存错误

c# - 如何使用 Azure 存储 SDK 将 Azure 文件存储上的文件从一个子文件夹移动到另一个子文件夹?

c# - 在 Visual Studio 2013 中调试期间筛选对象列表