有人可以对此进行说明吗,我的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;
        }
    }

最佳答案

您不能直接绑定到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返回Length属性而不是Name值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9254054/

10-13 00:55