【发布时间】:2017-02-01 21:25:22
【问题描述】:
我发现this 文章展示了如何将 List 转换为 IEnumerable。有人可以向我解释一下是否可以将其转换为可供许多列表使用的通用函数?
例如,我有一个
public class City
{
public int CityId { get; set; }
public string CityName { get; set; }
}
public class State
{
public int StateId { get; set; }
public string StateName { get; set; }
public string StateAbbreviation { get; set; }
}
然后我有这两个列表,我想在其中显示一个下拉列表:
List<City> cities
List<State> states
我可以设置 2 种不同的方法来做类似的事情,但是我必须将此代码复制/粘贴到多个列表中,这不是我想要的。
public static IEnumerable<SelectListItem> GetCitiesSelectList()
{
IEnumerable<SelectListItem> cityList = GetCities().Select(x => new SelectListItem() { Text = x.CityName, Value = x.CityId.ToString() });
return qList;
}
我想知道是否有类似的东西,但能够传入任何类型的列表并传入列表的文本和值?我知道你可以用TModel 做点什么,但我并不完全理解它,希望有人能把我推向正确的方向。
【问题讨论】:
-
为什么是 StateName , CityName ?为什么不只是名字
标签: c# asp.net-mvc asp.net-mvc-5