zoukankan      html  css  js  c++  java
  • C# 排序 Json内容排序,按照字母大小进行排序

    话不多说,上代码:

    public static SortedDictionary<string, object> KeySort(JObject obj)
            {
                var res = new SortedDictionary<string, object>();
                foreach (var x in obj)
                {
                    if (x.Value is JValue) res.Add(x.Key, x.Value);
                    else if (x.Value is JObject) res.Add(x.Key, KeySort((JObject)x.Value));
                    else if (x.Value is JArray)
                    {
                        var tmp = new SortedDictionary<string, object>[x.Value.Count()];
                        for (var i = 0; i < x.Value.Count(); i++)
                        {
                            tmp[i] = KeySort((JObject)x.Value[i]);
                        }
                        res.Add(x.Key, tmp);
                    }
                }
                return res;
            }
    var MethodCont = new JObject {
                      new JProperty("deptNo","00000123"),//
                      new JProperty("warehouseNo","1100000001")//
                      ,new JProperty("abcad","")
                       ,new JProperty("abdcaz","")
                        ,new JProperty("1234","")
                        ,new JProperty("0123","")
                        ,new JProperty("0113","")
                    };
    //不排序
    var json2 = JsonConvert.SerializeObject(MethodCont);
    //排序
    var target = KeySort(MethodCont);
    var json = JsonConvert.SerializeObject(target, Formatting.Indented);//缩进

    来吧,展示:

    1:不排序

    {
        "deptNo": "EBU0000000123",
        "warehouseNo": "1100000001",
        "abcad": "",
        "abdcaz": "",
        "1234": "",
        "0123": "",
        "0113": ""
    }

    2:排序,数字也是进行的排序的,

    {
        "0113": "",
        "0123": "",
        "1234": "",
        "abcad": "",
        "abdcaz": "",
        "deptNo": "EBU0000000123",
        "warehouseNo": "1100000001"
    }

    醍醐灌顶系列

    Dictionary<string, string> dic = new Dictionary<string, string>
                        {
                           { "access_token",access_token},
                           { "app_key",app_key },
                           { "method",method },
                           { "timestamp",timestamp },
                           { "v",v },
                         };
    
    var dicOrderby = string.Join("&", dic.OrderBy(p => p.Key).Select(p => $"{p.Key}{p.Value}"));

    这里dic.OrderBy就是进行排序的操作,dic是Dictiopnary类型,是一个字典,字典就是进行排序嘛,按照字母顺序之类的

    排好顺序后,然后就是开始Select所需要的内容了。

    string.Join("&",""),是可以设置链接符

    String.Join 方法 (String, String[])

    方法参考

  • 相关阅读:
    php yield学习笔记(一)
    EasySwoole的ContextManager的分析和使用
    Easyswoole的WaitGroup和Csp组件的分析和使用
    Laravel Event的分析和使用
    Laravel驱动管理类Manager的分析和使用
    Laravel Exception结合自定义Log服务的使用
    vue基础
    vue.js
    改善项目组织
    MongoDB 4.0版
  • 原文地址:https://www.cnblogs.com/ZkbFighting/p/13830528.html
Copyright © 2011-2022 走看看