使用嵌套数组将集合插入到列表中

时间:2016-09-21 14:39:55

标签: c# mongodb winforms

我有这个集合

    db.UserWatchtbl.insert( { 
fbId: "", 
Name: "user1", 
pass: "pass1",
Watchtbl: 
    [ 
        { 
        wid: "1350",
        name: "bought stock1",
        Symboles: [ { Name: "AAA" }, { Name: "BSI" } ] 
        },
        { 
        wid: "1350",
        name: "bought stock2",
        Symboles: [ { Name: "AAA" }, { Name: "BSI" }, { Name: "EXXI" } ] 
        }
    ]
} )

我尝试将其插入C#中的列表中,但我有一个嵌套数组watchtbl和symboles。我不知道如何将该元素放入列表或显示它 我试试这段代码

private async void Master_BindData()
    {
        // add user into datagridview from MongoDB Colelction Watchtbl
        var client = new MongoClient("mongodb://servername:27017");

        var database = client.GetDatabase("WatchTblDB");
        var collectionWatchtbl = database.GetCollection<BsonDocument>("UserWatchtbl");

        var filter = new BsonDocument();
        using (var cursor = await collectionWatchtbl.FindAsync(filter))
        {
            while (await cursor.MoveNextAsync())
            {
                var batch = cursor.Current;
                foreach (var document in batch)
                {

                    user.Add(new UserWatchTblCls()
                    {
                        Id = ObjectId.Parse(document["_id"].ToString()),
                        Name = document["Name"].ToString()
                        //WatchTbls = document["Watchtbl"].AsBsonArray;
                    });
                }
            }
        }
    }

和UserWatchTblCls()类

public class UserWatchTblCls
    {
        [BsonId]
        public ObjectId Id { get; set; }
        public string fbId { get; set; }
        public string Name { get; set; }
        public string Pass { get; set; }
        public List<WatchTblCls> WatchTbls { get; set; }
    }

    public class WatchTblCls
    {
        public string WID { get; set; }
        public string Name { get; set; }
        public List<SymboleCls> Symbols { get; set; }
    }

    public class SymboleCls
    {
        public string Name { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

您必须遍历Result的{​​{1}}。这会将数据收集到用户(FindAsync

List<UserWatchTblCls>

修改

喔。所以你也在寻找深度反序列化。

var user = new List<UserWatchTblCls>();

var cursor = collectionWatchtbl.FindAsync(filter).Result;
cursor.ForEachAsync(batch =>
{
    user.Add(new UserWatchTblCls()
    {
        Id = ObjectId.Parse(batch["_id"].ToString()),
        Name = batch["Name"].ToString()
    });
});