c# - 将值列表命名为字典以在 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; }
}
预期结果拉
解决方案
您正试图在迭代中输入一个条目。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; }
}
推荐阅读
- elasticsearch - Elasticsearch 6.x 中 number_of_routing_shards 的最大值
- swift - 格式化具有多个值的本地化字符串
- python - Keras 模型未使用模型 API 进行学习
- android - 无法安装“cordova-universal-clipboard”:
- javascript - Slim 3 在尝试从网页执行 POST 请求时为 getUploadedFiles() 返回 array(0)
- algorithm - 二维装箱变体的算法
- sql-server - Azure 备份未显示我的 SQL Server 数据库?
- android - 在android studio中错过资源
- python - 分布密度
- select - Select2 from select with required 不改变边框颜色。