【问题标题】:Sorting Dictionary by Value C#按值排序字典C#
【发布时间】:2017-06-02 21:24:46
【问题描述】:

我正在将 JSON 字符串反序列化为 C# 中的字典,但是我想按值对字典进行排序,以便将其显示在高分表上。现在字典按固定顺序返回。

  var temp = Json.Deserialize(www.text) as Dictionary<string,object>;
            if (temp != null)
            {
                data = (List<object>)temp["_items"];
            }

JSON 字符串

   "_items":[  
      {  
         "_updated":"Thu, 01 Jan 1970 00:00:00 GMT",
         "_id":"-",
         "Name":"John Doe",
         "_links":{  
            "self":{  
               "href":"Players/-",
               "title":"Player"
            }
         },
         "_created":"Thu, 01 Jan 1970 00:00:00 GMT",
         "FacebookId":XXXXX,
         "HighScore":8862,
         "_etag":"-"
      },
      {  
         "_updated":"Thu, 01 Jan 1970 00:00:00 GMT",
         "_id":"-",
         "Name":"John Smith",
         "_links":{  
            "self":{  
               "href":"Players/-",
               "title":"Player"
            }
         },
         "_created":"Thu, 01 Jan 1970 00:00:00 GMT",
         "FacebookId":XXXXXX,
         "HighScore":32000,
         "_etag":"-"
      }
   ],

细胞创建

var dict = (Dictionary<string, object>) data[row];


            // Set Name
            cell.nameText.text = dict["Name"].ToString();

            // Set score
            cell.score.text = string.Format("{0:n0}", dict["HighScore"]);

            // Fb Profile IMG
            StartCoroutine(getFBPicture(cell.image, dict["FacebookId"].ToString()));

【问题讨论】:

  • @ISHIDA 通过 JSON 中显示的 HighScore 变量
  • “现在字典按固定顺序返回”——嗯,不是按照明确定义的、记录在案的顺序。您应该将Dictionary&lt;,&gt; 视为无序集合。例如,您现在看到的任何特定顺序保证是您在另一个版本中看到的顺序。 (添加或删除一个项目可能会改变整个订单。)
  • 在我看来,明智的做法是创建一个类型(例如 Player)来将每个值反序列化为...,而不是 Dictionary&lt;string, object&gt;

标签: c# json linq dictionary


【解决方案1】:

试试这个。

public class obj 
                {
                public DateTime updated {get;set;}
                public string id {get;set;}
                public string Name {get;set;}
                 public self links {get;set;}
                public string FacebookId {get;set;}
                public int highscore {get;set;}

                }

    public class self {
    public string href {get;set;}
    public string title {get;set;}
                   }

                var dic = new Dictionary<TKey, obj>();
                var sorted = dic.OrderBy(x=>x.Value.highscore).ToList();

【讨论】:

    【解决方案2】:

    当您使用字典时,无法对字典本身进行排序,因为字典的目的是使用哈希值访问它。 但是,您可以通过执行以下操作返回排序值列表:

    dictionary.Values.OrderyBy(x => (DateTime)x._updated);
    

    这是假设您正在使用类似 Newtonsoft.Json 的东西,它返回一个具有可访问属性的对象。

    请考虑您应该使用基本类型的对象或实现 IComparable 的类型作为定义排序顺序的对象。

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 2017-02-02
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      相关资源
      最近更新 更多