2010-07-30 110 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));