首页 > 解决方案 > 将值列表命名为字典以在 MongoDB 中导入

问题描述

我遇到了一个问题,我需要将列表转换为 Dictionary > BsonDocument 以导入 MongoDB。

该列表具有列的名称和要插入该列的值。但是一旦编译器进入循环,我就会得到密钥已经退出异常。有什么建议吗?

void Main()
{
    List<ListRow> myList = new List<ListRow>();
    myList.Add(new ListRow { columnName = "column1", results = new List<string> { "a1", "b1", "c1" } });
    myList.Add(new ListRow { columnName = "column2", results = new List<string> { "a2", "b2", "c2" } });
    myList.Add(new ListRow { columnName = "column3", results = new List<string> { "a3", "b3", "c3" } });

    List<BsonDocument> batch = new List<BsonDocument>();
    foreach (var row in myList)
    {
        var dictionary = row.results.ToDictionary(x => row.columnName, x => x);
        batch.Add(dictionary);
    }
    // Print batch
    // Add to MongoDB
}

public class ListRow
{
    public string columnName { get; set; }
    public List<string> results { get; set; }
}

预期结果拉

在此处输入图像描述

标签: c#mongodb

解决方案


您正试图在迭代中输入一个条目。ToDictionary旨在创建整个字典。

class Program
{
    static void Main(string[] args)
    {
        List<ListRow> myList = new List<ListRow>
        {
            new ListRow {columnName = "column1", results = new List<string> {"a1", "b1", "c1"}},
            new ListRow {columnName = "column2", results = new List<string> {"a2", "b2", "c2"}},
            new ListRow {columnName = "column3", results = new List<string> {"a3", "b3", "c3"}}
        };

        BsonDocument batch = myList.ToDictionary(x => x.columnName, x => x.results).ToBsonDocument();
        // Print batch
        // Add to MongoDB
    }
}

public class ListRow
{
    public string columnName { get; set; }
    public List<string> results { get; set; }
}

推荐阅读