使用Linq对JSON对象进行排序 [英] Sorting a JSON Object using Linq

查看:82
本文介绍了使用Linq对JSON对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Google Search Appliance建议服务获得了以下格式的JSON响应

I am getting a response back from a Google Search Appliance suggest service in the form of JSON in the following format

string jsonString = @"{ ""query"": ""t"", ""results"": [ { ""name"": ""tom"", ""type"": ""suggest"" }, { ""name"": ""tim"", ""type"": ""suggest"" }]}";

我想按名称的字母顺序对结果列表进行排序,然后将名称更改为句子大小写. 我可以在jquery中执行此操作,但出于性能方面的考虑,宁愿在服务器端执行此操作.

I want to sort the results list by name alphabeticaly and change the names to sentence case. I can do this in jquery but would prefer to do it on the server side for performance reasons.

我可以对结果进行排序,但是返回一个IEnumarable<Result>,但是我似乎无法对正在序列化的对象内的结果进行排序.

I can sort the results but that returns an IEnumarable<Result> but I cant seem to sort the results within the object that is being serialised.

 string jsonString = @"{ ""query"": ""t"", ""results"": [ { ""name"": ""tom"", ""type"": ""suggest"" }, { ""name"": ""tim"", ""type"": ""suggest"" }]}";

JObject json = JObject.Parse(jsonString);

        var gsaSuggestions = JsonConvert.DeserializeObject<GSASuggestion>(jsonString);

        var orded = gsaSuggestions.ResultList.OrderBy<Result, string>(r => r.Name);

        string output = JsonConvert.SerializeObject(gsaSuggestions);
    }

    [JsonObject(MemberSerialization.OptOut)]
    public class GSASuggestion
    {
        [JsonProperty(PropertyName = "query")]
        public string Query {get; set;}
        [JsonProperty(PropertyName = "results")]
        public List<Result> ResultList {get; set;}
    }

    public class Result
    {
        [JsonProperty(PropertyName = "name")]
        public string Name {get; set;}
        [JsonProperty(PropertyName = "type")]
        public string Type {get; set;}
    }

结果应为:

{ "query": "t", "results": [ { "name": "Tim", "type": "suggest" }, { "name": "Tom", "type": "suggest" }]};

推荐答案

您实际上并没有使用OrderBy的返回值.试试:

You don't actually use the return value of OrderBy. Try:

gsaSuggestions.ResultList =
    gsaSuggestions.ResultList.OrderBy<Result, string>(r => r.Name).ToList();

请记住,OrderBy将按顺序返回结果的新序列,并且不会修改原始序列.如果要对gsaSuggestions.ResultList进行排序,则需要为其分配一个排序列表.

Remember, OrderBy returns a new sequence with the results in order, and does not modify the original sequence. If you want gsaSuggestions.ResultList to be sorted then you will need to assign a sorted list to it.

您还可以使用 List.Sort 进行就地排序>:

You could also do an in-place sort using List.Sort:

gsaSuggestions.ResultList.Sort((x, y) => x.Name.CompareTo(y.Name));

这篇关于使用Linq对JSON对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆