[英]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.