2010-07-30 169 views
2

我从谷歌Search Appliance的得到一个响应返回一个JSON对象提出的服务以JSON的形式按以下格式排序使用LINQ

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

我想按名称搜索结果列表alphabeticaly排序和变化判决案件的名字。 我可以在jQuery中做到这一点,但出于性能原因,宁愿在服务器端做到这一点。

我可以排序结果,但返回IEnumarable<Result>,但我似乎无法排序正在序列化的对象内的结果。

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

回答

8

你不实际使用排序依据的返回值。请尝试:

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

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

你也可以做某种使用List.Sort就地:

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