将元素插入字符串列表

时间:2017-08-24 07:28:12

标签: c# mongodb

当我使用第一个代码时,它完美地在DB中提供单词

collection.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X.GetElement("word").Value) );

但是当我尝试通过将所有“单词”放入字符串列表来获取单个元素时,它会给出ArgumentOutOfRangeException错误。

collection.Find(new BsonDocument()).ForEachAsync(X => wordStringList.Add(X.GetElement("word").Value.ToString()) );
Console.WriteLine(wordStringList[0]);

我该如何解决这个问题,谢谢。

2 个答案:

答案 0 :(得分:0)

由于使用了wordStringList.Add,因此Console.WriteLine来电 ForEachAsync来之后,您的ForEachAsync来电将会运行,因此您的问题可能会出现竞争情况。您可await Select获得预期结果,也可以使用Select

以下是var wordStringList = collection.Find(new BsonDocument()) .Select(X => X.GetElement("word").Value)) .ToList(); Console.WriteLine(wordStringList[0]); 方法的示例。

<bgo:Sample>
    <bgo:Date>23</bgo:Date>
    <bgo:Month>4</bgo:Month>
    <bgo:Year>2016</bgo:Year>
<bgo:Sample>

当然,这假设您在列表中至少有一个值。

答案 1 :(得分:0)

我猜是因为你使用的是异步方法,所以当你尝试写出第一个元素时,它还没有完成(甚至没有启动)。所以列表仍然是空的。 您可能需要等待异步方法首先使用await.Wait()完成,具体取决于上下文

await collection.Find(new BsonDocument()).ForEachAsync(X => wordStringList.Add(X.GetElement("word").Value.ToString()) );
Console.WriteLine(wordStringList[0]);

collection.Find(new BsonDocument()).ForEachAsync(X => wordStringList.Add(X.GetElement("word").Value.ToString())).Wait();
Console.WriteLine(wordStringList[0]);

await关键字只能在异步方法中使用,而.Wait()将在异步和非异步方法中都有效。

我对该主题的了解不足以解释await.Wait()之间的区别,因此您需要在其他地方查看,但我要了解<{1}}在可用时是首选。