chiiefs chiiefs - 6 days ago 8
JSON Question

C# Transform list from one type to another

I'm working on displaying some data onto a table with C# MVC 5 razor. The data I'm using (and cannot be changed) looks like this in 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
}
]


Which resolves to this table:

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


I'm deserializing this json into a list of objects, but can't get the formatting changed. I want the table to look like this in the view:

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


I've tried multiple for loops and linq selects, but not able to get it.
Here's what I've got:

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;


Somebody please point me in the right direction with this select statement. Thank you!

Answer

Assuming you will always have the same set of cities, you could do:

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 }
}