有人可以阐明我的 NameValueCollection 返回 Length 属性而不是 Name 和 Value 可以告诉我我在这里做错了什么。我无法为下拉列表设置 DataTextField 或 DataValueField,它只是给我长度。
public NameValueCollection GetDisplayForumGroups()
{
using (CMSEntities db = new CMSEntities())
{
var forums = (from x in db.Forums where x.ParentID == null select new { Name = x.Title, Value = x.ForumID });
NameValueCollection collection = new NameValueCollection();
foreach (var forum in forums)
{
collection.Add(forum.Name, forum.Value.ToString());
}
return collection;
}
}
public Dictionary<string, int> GetDisplayForumGroups()
{
using (CMSEntities db = new CMSEntities())
{
Dictionary<string, int> forums = (from x in db.Forums where x.ParentID == null select x).ToDictionary(x => x.Title, x => x.ForumID);
return forums;
}
}
最佳答案
您不能直接绑定(bind)到 NameValueCollection
,因为它不提供合适的枚举器。标准枚举器仅通过键枚举。
然后你不应该首先使用 NameValueCollection
,你应该使用通用的 Dictionary
除非你需要每个键的多个值(甚至那么在大多数情况下会有更好的选择)。甚至还有一种用于自动制作字典的 Linq 方法:
Dictionary<string, int> forums = (from x
in db.Forums
where x.ParentID == null
select x)
.ToDictionary(x => x.Title, x => x.ForumID);
关于c# - NameValueCollection 返回长度属性而不是名称值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254054/