首页 > 解决方案 > 如何将列表转换为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# 中做到这一点?

标签: c#mongodbasp.net-core

解决方案


应该是这样的;

dynamic ticketDetails = new ExpandoObject();
ticketDetails.user = collection;

string json = Newtonsoft.Json.JsonConvert.SerializeObject(ticketDetails);

推荐阅读