2

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"" }]}";

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.

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;}
    }

the result should be:

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

1 Answer 1

10

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

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

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.

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

gsaSuggestions.ResultList.Sort((x, y) => x.Name.CompareTo(y.Name));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.