sky*_*oot 2 c# linq-to-objects json.net
我收到了来自Google Search Appliance的回复,建议采用以下格式的JSON形式的服务
string jsonString = @"{ ""query"": ""t"", ""results"": [ { ""name"": ""tom"", ""type"": ""suggest"" }, { ""name"": ""tim"", ""type"": ""suggest"" }]}";
Run Code Online (Sandbox Code Playgroud)
我想按字母顺序对结果列表进行排序,并将名称更改为句子大小写.我可以在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;}
}
Run Code Online (Sandbox Code Playgroud)
结果应该是:
{ "query": "t", "results": [ { "name": "Tim", "type": "suggest" }, { "name": "Tom", "type": "suggest" }]};
Run Code Online (Sandbox Code Playgroud)
您实际上并未使用OrderBy的返回值.尝试:
gsaSuggestions.ResultList =
gsaSuggestions.ResultList.OrderBy<Result, string>(r => r.Name).ToList();
Run Code Online (Sandbox Code Playgroud)
请记住,OrderBy按顺序返回包含结果的新序列,并且不会修改原始序列.如果要gsaSuggestions.ResultList进行排序,则需要为其分配排序列表.
您还可以使用List.Sort进行就地排序:
gsaSuggestions.ResultList.Sort((x, y) => x.Name.CompareTo(y.Name));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6648 次 |
| 最近记录: |