I need to create a line graph for each store in every month of the year. However, store is dynamic it depends on the merchant. This is the return query from the db:
[{"Month":"January","Total":44,"Store":"Refoil"},
{"Month":"January","Total":242,"Store":"Sustainable Salons"},
{"Month":"January","Total":99,"Store":"The Base Collective"},
{"Month":"February","Total":37,"Store":"Refoil"},
{"Month":"February","Total":219,"Store":"Sustainable Salons"},
{"Month":"February","Total":122,"Store":"The Base Collective"},
{"Month":"February","Total":148,"Store":"Watersco Australia"}]
How can I return an object this like:
[{"Month":"January","Refoil":44,"Sustainable Salons":242},
{"Month":"February","Refoil":2,"Sustainable Salons":10}]
You could use an ExpandoObject
to transpose the results:-
var results = new List<Result>();
results.Add(new Result() { Month = "January", Total = 44, Store = "Refoil" });
results.Add(new Result() { Month = "January", Total = 242, Store = "Sustainable Salons" });
results.Add(new Result() { Month = "January", Total = 99, Store = "The Base Collective" });
results.Add(new Result() { Month = "February", Total = 37, Store = "Refoil" });
results.Add(new Result() { Month = "February", Total = 219, Store = "Sustainable Salons" });
results.Add(new Result() { Month = "February", Total = 122, Store = "The Base Collective" });
results.Add(new Result() { Month = "February", Total = 148, Store = "Watersco Australia" });
var transpose = results.GroupBy(x => x.Month).Select(x =>
{
dynamic e = new ExpandoObject();
e.Month = x.Key;
var ed = e as IDictionary<string, object>;
x.ToList().ForEach(y => ed.Add(y.Store, y.Total));
return e;
});
Debug.WriteLine(JsonConvert.SerializeObject(transpose, Newtonsoft.Json.Formatting.Indented));
Result
class:-
public class Result
{
public string Month { get; set; }
public string Store { get; set; }
public int Total { get; set; }
}
Gives the following output:-
[
{
"Month": "January",
"Refoil": 44,
"Sustainable Salons": 242,
"The Base Collective": 99
},
{
"Month": "February",
"Refoil": 37,
"Sustainable Salons": 219,
"The Base Collective": 122,
"Watersco Australia": 148
}
]
Deserialize your json to c# object refer Deserializing JSON data to C# using JSON.NET
Group by month using linq and json serialize your c# object and send it to your client side..
If this doesn't help, please provide more details, what would you expect after group by your data by month?.
Map db response into c# model, and than create anonymous object with needed structure and serialize with Json.Net. If this not result you want, please add more details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.