繁体   English   中英

如何从 bson 文档中的键中获取值以放入 ListBox (C#)

[英]How to get the values from keys in bson document in order to put in a ListBox (C#)

我是 C#/.NET 的新手,我一直在尝试在字典应用程序中实现数据库服务器(仅用于学习目的),您可以在其中从列表框中选择单词并在文本框中显示值。 我正在尝试仅获取名为“Word”和“Translation”的键的列表到字符串

这是 bson(json) 文件

{
  "_id": "5ca01f8e36601d012c7b2da1",
  "Word": "Bonjour",
  "Translation": "Hello",
  "Word_Type": "Something",
  "Synonyms": "Salut",
  "Use_Cases": "Bonjour, comment vas-tu?",
  "Definition": "It's a Greeting"
}

这是我用来从数据库中获取数据的代码:

        private MongoClient client = new MongoClient("mongodb://localhost:27017");

        /// <summary>
        /// All the data needed for words
        /// </summary>
        public class DWord
        {
            public ObjectId _id { get; set; }
            public string Word { get; set; }
            public string Translation { get; set; }
            public string Word_Type { get; set; }
            public string Synonyms { get; set; }
            public string Use_Cases { get; set; }
            public string Definition { get; set; }
        }

        private void MethodThatGetsData()
        {
            var database = client.GetDatabase("DictDB");
            var collection = database.GetCollection<BsonDocument>("Words");
            var records = collection.Find(new BsonDocument()).ToList();

            // I tried using foreach, but I don't know how to get the keys in that bsondocument (called "record" below)
            foreach (string record in records)
            {
                WordsListBox.Items.Add(record);
            }

        }

我想知道如何获取每条记录的键值,感谢您的帮助

用这样的东西替换你的循环:

foreach (BsonDocument record in records)
{
    IEnumerable<string> names = record.Names;
    // Do something with the names...
}

请注意,通过记录枚举为每个查找结果返回一个 BsonDocument。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM