简体   繁体   English

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

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

I'm new to C#/.NET and i've been trying to implement a database server (just for learning purposes) in a dictionary application where you can select words from a listbox and it will display the values in text boxes.我是 C#/.NET 的新手,我一直在尝试在字典应用程序中实现数据库服务器(仅用于学习目的),您可以在其中从列表框中选择单词并在文本框中显示值。 I'm trying to get a list of only the keys called "Word" and "Translation" to strings我正在尝试仅获取名为“Word”和“Translation”的键的列表到字符串

this is the bson(json) document这是 bson(json) 文件

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

and this is the code i'm using to get the data from database:这是我用来从数据库中获取数据的代码:

        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);
            }

        }

I want to know how to get the key values for each record, thanks for any help我想知道如何获取每条记录的键值,感谢您的帮助

Replace your loop with something like this:用这样的东西替换你的循环:

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

Note, enumerating through records returns a BsonDocument for every find result.请注意,通过记录枚举为每个查找结果返回一个 BsonDocument。

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

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