c# - 如何将列表转换为c#中的expandobject键?
问题描述
我有一个函数,我从 db 获取数据(对象数组),然后将这些数组对象一个接一个地添加到一个类型中ExpandoObject
public async Task<List<ExpandoObject>> GetGroupWithMaxTickets(){
List<ExpandoObject> topGroupsWithMaxTickets = new List<ExpandoObject>();
dynamic ticketDetails = new ExpandoObject();
var pipeline_tickets = new BsonDocument[]{
new BsonDocument("$match",
new BsonDocument
{
{ "nsp", "/sbtjapan.com" },
{ "datetime",
new BsonDocument
{
{ "$gte", "2019-12-03T00:00:34.417Z" },
{ "$lte", "2019-12-03T24:00:34.417Z" }
} }
}),
new BsonDocument("$group",
new BsonDocument
{
{ "_id", "$group" },
{ "totalTIckets",
new BsonDocument("$sum", 1) }
}),
new BsonDocument("$project",
new BsonDocument
{
{ "_id", 0 },
{ "group", "$_id" },
{ "totalTIckets", 1 }
}),
new BsonDocument("$sort",
new BsonDocument("totalTIckets", -1)),
new BsonDocument("$limit", 5)
};
var collection = await DbService.tickets.AggregateAsync<RawBsonDocument>(pipeline_tickets, new AggregateOptions {UseCursor = true, BatchSize = 500});
await collection.MoveNextAsync();
if(collection.Current.ToList().Count > 0){
// ticketDetails = JsonConvert.DeserializeObject(collection.Current.ToJson());
// ticketDetails.group = collection.Current.ToList()[0]["group"];
// ticketDetails.totalTickets = collection.Current.ToList()[0]["totalTIckets"];
Parallel.ForEach(collection.Current.ToList(), (ticket) => {
Console.WriteLine("Ticket----"+ticket);
dynamic groupWithTickets = new ExpandoObject();
groupWithTickets = ticket;
topGroupsWithMaxTickets.Add(groupWithTickets);
});
}
return topGroupsWithMaxTickets;
}
但它会抛出这样的错误
System.AggregateException: One or more errors occurred. (The best overloaded method match for 'System.Collections.Generic.List<System.Dynamic.ExpandoObject>.Add(System.Dynamic.ExpandoObject)' has some invalid arguments)
我希望我的函数必须返回类型的对象数组List<ExpandoObject>
我怎么能在 C# 中做到这一点?
解决方案
应该是这样的;
dynamic ticketDetails = new ExpandoObject();
ticketDetails.user = collection;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ticketDetails);
推荐阅读
- c# - 检索数据时 GET 请求时的 HTTP 405
- javascript - 如何实现我的 jQuery 代码以在我的网站上工作?
- javascript - Konva 中的平行线分隔符
- javascript - 在 React Child 中访问 Props 以映射数组?
- c++ - 在 C++17 中实现迭代器和 const_iterator 的正确方法是什么?
- python - 仅在重新启动 gunicorn 后才会显示对数据库的更改
- c - 如何对两个 32Q16 定点整数进行除法?
- extjs - 如何消除行的小计,但将总计留在 sencha 数据透视表上?
- c - 我应该使用 GetFileSize 还是 _stat64 在 Windows 上获取文件大小?
- python - 如何在烧瓶中返回数据类型(对象)