[英]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.