[英]When retrieving records from a MongoDb collection, do the records come back sorted based on the index that was set up for that collection?
[英]Retrieving item from List collection when each index have a set of items
我正在嘗試使用asp.net C#創建一個表單應用程序,顯示問題和提示。 我打算將這兩個放在一個單獨的列表集合中,但是問題和提示可能會脫節,所以我決定創建一個帶有ID,Q和Hint的類,然后將它們放入列表集合中。一套。
這是QHint.cs文件中的代碼:
public QHint (int ID, string Q, string Hint)
{
this.ID = ID;
this.Q = Q;
this.Hint = Hint;
}
public int ID { get; set; }
public string Q { get; set; }
public string Hint { get; set; }
這是form1.cs文件中的代碼:
List<QHint> QHintList = new List<QHint>;
QHintList.add(new QHint(1, "quesiton1 blah blah?", "hint1 blah blah"));
QHintList.add(new QHint(2, "quesiton2 blah blah?", "hint2 blah blah"));
.... and so on....
我的問題是如何指定從列表中檢索的項目,例如hint1? 我試圖用QHintList [0]檢索一個集合(ID,Q和Hint)但是甚至無法做到這一點。 但是,最終我希望能夠顯示問題1,然后當用戶點擊提示按鈕時,我可以顯示相應的提示1。 另外,使用類並列出邏輯上最好的方法來完成我想要的東西?
這可能是一些基本知識,我嘗試查找如何使用列表,如何從列表中檢索數據,等等但沒有運氣。
任何幫助都感激不盡。
如果您可以跟蹤哪些位置的提示,那么您可以使用
var qHint = QHintList[i];
如果你無法保持跟蹤,那么你可以在List上使用帶有謂詞的find方法。 我認為這將有效(取決於您當時可獲得的信息)
var qHint = QHintList.Find(q => q.Id == YourId);
為什么不創建字典以提高性能
Dictionary<int, QHint> QHintList = new Dictionary<int, QHint>;
QHintList.add(1, new QHint(1, "quesiton1 blah blah?", "hint1 blah blah"));
QHintList.add(2, new QHint(2, "quesiton2 blah blah?", "hint2 blah blah"));
然后你就可以這樣打電話;
int questionId = 1;
QHintList[questionId].Hint
var hint = QHintList[0].Hint;
Console.WriteLine(hint);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace QuestHint
{
class QHint
{
public QHint() { }
public QHint(int ID, string Q, string Hint)
{
this.ID = ID;
this.Q = Q;
this.Hint = Hint;
}
public int ID { get; set; }
public string Q { get; set; }
public string Hint { get; set; }
public List<QHint> QHintList = new List<QHint>();
}
class Program
{
static void Main(string[] args)
{
QHint q = new QHint();
q.QHintList.Add(new QHint(1, "quesiton1 blah blah?", "hint1 blah blah"));
q.QHintList.Add(new QHint(42, "quesiton2 blah blah?", "hint2 blah blah"));
int magicNumber = 42;
Debug.WriteLine(q.QHintList[0].Q); // output quesiton1 blah blah?
Debug.WriteLine(q.QHintList.Find(obj => obj.ID == magicNumber).Hint); //hint2 blah blah
// you are saying like: find me the obj, where the ID of that obj is equals my magicNumber. And from that found object, give me the field Hint.
}
}
}
嘗試使用Linq
var hint = QHintList.First(p=>p.ID == inputId).Hint
如果我的方向正確,那么你需要在Property Hint中找到文本hint1。 如果是多個
foreach QHint q in QHintList
{
if(q.Hint.Contains("hint1"))
{
// then do something cool;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.