[英]How to return object with dynamic fields
我需要在一年中的每個月為每個商店創建一個折線圖。 但是,商店是動態的,它取決於商家。 這是來自數據庫的返回查詢:
[{"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"}]
我怎樣才能返回這樣的對象:
[{"Month":"January","Refoil":44,"Sustainable Salons":242},
{"Month":"February","Refoil":2,"Sustainable Salons":10}]
您可以使用ExpandoObject
轉置結果:-
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
類:-
public class Result
{
public string Month { get; set; }
public string Store { get; set; }
public int Total { get; set; }
}
給出以下輸出:-
[
{
"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 參考Deserializing JSON data to C# using JSON.NET
使用 linq 和 json 按月分組序列化您的 c# 對象並將其發送到您的客戶端..
如果這沒有幫助,請提供更多詳細信息,按月對數據進行分組后您會期望什么?。
將 db 響應映射到 C# 模型,然后創建具有所需結構的匿名對象並使用 Json.Net 進行序列化。 如果這不是您想要的結果,請添加更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.