如何将新项目插入 IEnumerable
我从 Enum 创建一个下拉列表。
public enum Level
{
Beginner = 1,
Intermediate = 2,
Expert = 3
}
这是我的扩展。
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
var result = from TEnum e in values
select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
var tempValue = new { ID = 0, Name = "-- Select --" };
return new SelectList(result, "Id", "Name", enumObj);
}
我遇到的问题是将另一个项目插入 IEnumerable 中。我只是不知道该怎么做。有人可以修改我的代码以在顶部插入“--select--”吗?
I create a dropdownlist from Enum.
public enum Level
{
Beginner = 1,
Intermediate = 2,
Expert = 3
}
here's my extension.
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
var result = from TEnum e in values
select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
var tempValue = new { ID = 0, Name = "-- Select --" };
return new SelectList(result, "Id", "Name", enumObj);
}
the problem I have is to insert antoher item into IEnumerable. I just could not figure out how to do it. Can someone please modify my code to insert "--select--" to the top.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法修改
IEnumerable
对象,它仅提供枚举元素的接口。但是您可以使用.ToList()
将IEnumerable
转换为List
。我不确定这是否是您想要的:
You can't modify a
IEnumerable<T>
object, it only provides an interface to enumerate elements. But you could use.ToList()
to convert theIEnumerable<T>
to aList<T>
.I'm not sure if this is what you want:
您无法修改 IEnumerable。顾名思义,它允许仅向前的枚举遍历。
话虽如此,这似乎是一个 ASP.NET MVC 应用程序。实现下拉菜单想要实现的目标(插入默认值)的正确方法是使用 DropDownFor 帮助器的正确重载,如下所示:
这显然假设您的扩展方法非常简单:
You cannot modify an IEnumerable. As it name suggests it allows a forward-only enumeration traversal.
This being said it seems that this is an ASP.NET MVC application. The correct way to achieve what you are trying to achieve (insert a default value) for a dropdown is to use the proper overload of the DropDownFor helper, like this:
This obviously assumes that your extension method is as simple as:
尝试一下
Give this a try