Use*_*rol 6 .net sorting dictionary asp.net-web-api asp.net-web-api2
我有一系列键/值对,我想要返回自定义排序(不是按键):
public IHttpActionResult GetStuff() {
bla-bla-bla
.ToDictionary(x => x.Code, x => x.Desc);
}
Run Code Online (Sandbox Code Playgroud)
生成以下JSON:
{
"1": "ZZZ",
"3": "AAA",
"8": "CCC",
}
Run Code Online (Sandbox Code Playgroud)
响应始终由密钥排序,因为据我所知Dictionary<K, T>,不保证特定的排序.如果我改为返回已排序的KeyValuePair<K, T>Web API 列表,则会生成另一个布局:
[
{ "Key": 3, "Value": "AAA"},
{ "Key": 8, "Value": "CCC"},
{ "Key": 1, "Value": "ZZZ"},
]
Run Code Online (Sandbox Code Playgroud)
由于额外的有效载荷,我不想要.那么如何返回类似于第一个样本的类似字典的键/值序列?
您可以使用Select()方法将字典的输出更改为特定的 ViewModel。对于样品:
public class SourceViewModel
{
public string Key { get; set; }
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Ok方法来响应 200 http 状态代码,例如:
public IHttpActionResult GetStuff()
{
return Ok(source.Select(x => new SourceViewModel { Key = x.Code, Value = x => x.Desc})
.ToList());
}
Run Code Online (Sandbox Code Playgroud)