首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按Enum排序NameValueCollection

按Enum排序NameValueCollection
EN

Stack Overflow用户
提问于 2010-02-23 08:57:22
回答 3查看 2.2K关注 0票数 0

我必须对枚举(项,通常为5到15)与枚举(,其项超过60项)进行排序。现在我正在使用这个扩展函数,任何人都有更好的想法来编写这段代码.

代码语言:javascript
复制
    public static NameValueCollection Sort(this NameValueCollection queryString, Type orderByEnumType, bool excludeZeroValues)
    {
        NameValueCollection _processedQueryString = HttpUtility.ParseQueryString("");
        if (queryString.HasKeys())
        {
            SortedList<int, KeyValuePair<string, string>> querySortedList = new SortedList<int, KeyValuePair<string, string>>();
            string[] enumKeys = Enum.GetNames(orderByEnumType);
            int counter = 1000;
            foreach (string key in queryString)
            {
                string value = queryString[key];
                if (enumKeys.Contains(key, StringComparer.CurrentCultureIgnoreCase))
                {
                    int order = (int)Enum.Parse(orderByEnumType, key, true);
                    querySortedList.Add(order, new KeyValuePair<string, string>(key, value));
                }
                else
                {
                    querySortedList.Add(counter, new KeyValuePair<string, string>(key, value));
                    counter++;
                }
            }
            foreach (KeyValuePair<int, KeyValuePair<string, string>> kvp in querySortedList)
            {
                if (!kvp.Value.Value.IsNullOrEmpty() && !kvp.Value.Key.IsNullOrEmpty())
                {
                    if (!excludeZeroValues || kvp.Value.Value != "0")
                    {
                        _processedQueryString.Add(kvp.Value.Key, System.Web.HttpUtility.UrlEncode(kvp.Value.Value));
                    }
                }
            }
        }
        return _processedQueryString;
    }

这个是这样工作的

代码语言:javascript
复制
    public enum OrderEnum
    {
        key1=1,
        key2=20,
        key3=3,
        //note
        key4=100,
        key5=2,
        key6=6,
        key7,
        key8,
        key9 
    }
    public void Test()
    {
        NameValueCollection col1 = new NameValueCollection();
        col1.Add("key1", "value1");
        col1.Add("key9", "value1");
        col1.Add("key3", "value1");
        col1.Add("key5", "value1");
        Response.Write(col1.Sort(typeof(OrderEnum)).ToString());
        //out put: key1=value1&key5=value1&key3=value1&key9=value1
    }

这也应该是可行的

代码语言:javascript
复制
public void Test2()
    {
        NameValueCollection col1 = new NameValueCollection();
        col1.Add("key1", "value1");
        col1.Add("key-x", "value1");
        col1.Add("key-y", "value1");
        col1.Add("key9", "value1");
        col1.Add("key3", "value1");
        col1.Add("key5", "value1");
        col1.Add("key-z", "value1");
        Response.Write(col1.Sort(typeof(OrderEnum)).ToString());
        //out put: key1=value1&key5=value1&key3=value1&key9=value1&key-x=value1&key-y=value1&key-z=value1
    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-02-23 09:28:44

我认为更好的做法是将你的名字转换成键值列表,并通过操作应用一个简单的LINQ顺序,这是快速和简单的。

添加一个新的扩展方法,将您的namevaluecoll转换为keyvaluepairs列表。

代码语言:javascript
复制
    public static List<KeyValuePair<string, string>> ToPairs(this System.Collections.Specialized.NameValueCollection collection)
    {
        if (collection == null)
        {
            throw new ArgumentNullException("collection");
        }

        return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key])).ToList();
    } 

然后在这个对象上应用linq order,如下所示

代码语言:javascript
复制
        System.Collections.Specialized.NameValueCollection col1= new System.Collections.Specialized.NameValueCollection();
        col1.Add("key1", "value1");
        col1.Add("key-x", "value2");
        col1.Add("key-y", "value3");
        col1.Add("key9", "value4");
        col1.Add("key3", "value5");
        col1.Add("key5", "value6");
        col1.Add("key-z", "value7"); 

        var nvc = col1.ToPairs();

        // To order the items based on key in descending order
        var orderedbykey=nvc.OrderByDescending(x => x.Key).ToList();  

       // To order the items based on value in descending order           
       var orderedbyval=nvc.OrderByDescending(x => x.Value).ToList();

       //or order by ur custom enum key
        var orderbyEnumKeys = colc.OrderBy(x =>
        {
            int en;
            try
            {
                 en = (int)Enum.Parse(typeof(OrderEnum), x.Key);
            }
            catch (Exception ex)
            {
                return int.MaxValue;
            }
            return en;
        }).ToList();

希望这有帮助..。

票数 1
EN

Stack Overflow用户

发布于 2010-02-23 09:33:18

你可以这样做:

代码语言:javascript
复制
public static NameValueCollection SortByEnum<TEnum>(this NameValueCollection source) where TEnum : struct
{
    var orderedKeys = source.Keys.Cast<string>().OrderBy(k => Enum.IsDefined(typeof(TEnum), k) ? Convert.ToInt32(Enum.Parse(typeof(TEnum), k)) : int.MaxValue);
    var ordered = new NameValueCollection();
    foreach(var key in orderedKeys) ordered.Add(key, source[key]);
    return ordered;
}
票数 0
EN

Stack Overflow用户

发布于 2010-02-23 11:04:33

最后,我用这个解决方案得出结论。

代码语言:javascript
复制
public static NameValueCollection SortByEnum<TEnum>(this NameValueCollection source) where TEnum : struct
{
    var orderedKeys = source.Keys.Cast<string>().OrderBy(k => ((Enum.IsDefined(typeof(TEnum), k)) ? ((int)Enum.Parse(typeof(TEnum), k)) : int.MaxValue));
    var ordered = HttpUtility.ParseQueryString("");
    foreach (var key in orderedKeys)
    {
        ordered.Add(key, source[key]);
    }
    return ordered;
}

这将解决我所有的问题谢谢托马斯@拉梅什

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2316840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档