NameValueCollection返回Length Property而不是Name Value

本文关键字:Name Value 返回 Length Property NameValueCollection | 更新日期: 2023-09-27 18:24:09

有人能说明这一点吗?我的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返回Length Property而不是Name Value

不能直接绑定到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);