C#将列表从一种类型转换为另一种类型

时间:2016-12-01 18:46:53

标签: c# json linq

我正在使用C#MVC 5 razor在桌面上显示一些数据。我正在使用(并且无法更改)的数据在JSON中看起来像这样:

[
    {
        "Status": "New",
        "Denver": 2,
        "Seattle": 0,
        "New York": 3,
        "El Paso": 0
    },
    {
        "Status": "In Progress",
        "Denver": 1,
        "Seattle": 2,
        "New York": 5,
        "El Paso": 1
    },
    {
        "Status": "Closed",
        "Denver": 12,
        "Seattle": 2,
        "New York": 1,
        "El Paso": 3
    }
]

哪个解析到此表:

+-------------+--------+---------+----------+---------+
|   Status    | Denver | Seattle | New York | El Paso |
+-------------+--------+---------+----------+---------+
| New         |      2 |       0 |        3 |       0 |
| In Progress |      1 |       2 |        5 |       1 |
| Closed      |     12 |       2 |        1 |       3 |
+-------------+--------+---------+----------+---------+

我将此json反序列化为对象列表,但无法更改格式。我希望表格在视图中看起来像这样:

+----------+-----+-------------+--------+
|          | New | In Progress | Closed |
+----------+-----+-------------+--------+
| Denver   |   2 |           1 |     12 |
| Seattle  |   0 |           2 |      2 |
| New York |   3 |           5 |      1 |
| El Paso  |   0 |           1 |      3 |
+----------+-----+-------------+--------+

我尝试了多个for循环和linq选择,但无法得到它。 这就是我所拥有的:

public class Response {
    public string Status { get; set; }
    public int Denver { get; set; }
    public int Seattle { get; set; }
    public int NewYork { get; set; }
    public int ElPaso { get; set; }
}

public class ViewModel {
    public string Name { get; set; }
    public int New { get; set; }
    public int InProgress { get; set; }
    public int Closed { get; set; }
}

List<Response> response = service.GetData();
if (response != null) {
    List<ViewModel> viewModels = response.Select(???);
}

return viewModels;

有人请用这个选择声明指出我正确的方向。谢谢!

1 个答案:

答案 0 :(得分:0)

假设您将拥有相同的城市集,您可以这样做:

var data = response.ToDictionary(x => x.Status, x => x);

var viewModels = new []
{
  new  ViewModel { Name = "Denver", New = data["New"].Denver, InProgress=data["In Progress"].Denver, Closed = data["Closed"].Denver },
  new  ViewModel { Name = "Seattle", New = data["New"].Seattle, InProgress=data["In Progress"].Seattle, Closed = data["Closed"].Seattle },
  new  ViewModel { Name = "New York", New = data["New"].NewYork, InProgress=data["In Progress"].NewYork, Closed = data["Closed"].NewYork },
  new  ViewModel { Name = "El Paso", New = data["New"].ElPaso, InProgress=data["In Progress"].ElPaso, Closed = data["Closed"].ElPaso }
}