Goo*_*ber 2 c# foreach hashtable
我有一些代码填充哈希表,其中一个问题作为键,一个答案的arraylist作为值.
我想从哈希表中打印出这些值,以便在哈希表中显示每个问题的问题和相应的解决方案.
我知道我已经用foreach循环做了一些完全愚蠢的事情来打印出哈希表的内容,但是我已经编写了好几个小时的编码,我想不出打印我的嵌套arraylist的逻辑.
非常感谢.
这是代码:
//Hashtable Declaration
static Hashtable sourceList = new Hashtable();
//Class For Storing Question Information
public class QuestionAnswerClass
{
public string simonQuestion;
public ArrayList simonAnswer = new ArrayList();
}
//Foreach loop which populates a hashtable with results from
//a linq query that i need to print out.
foreach (var v in linqQueryResult)
{
Debug.WriteLine(v.question);
newques.simonQuestion = v.question;
//Debug.WriteLine(v.qtype);
//newques.simonQType = v.qtype;
foreach (var s in v.solution)
{
Debug.WriteLine(s.Answer);
newques.simonAnswer.Add(s.Answer);
}
}
sourceList.Add(qTextInput,newques);
//foreach loop to print out contents of hashtable
foreach (string key in sourceList.Keys)
{
foreach(string value in sourceList.Values)
{
Debug.WriteLine(key);
Debug.WriteLine(sourceList.Values.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 10
当您使用LINQ时,您显然不受框架1.1的限制,因此您不应该使用HashTable和ArrayList类.您应该使用严格类型的泛型Dictionary和List类.
您不需要课程来保持问题和答案Dictionary.该类只是一个没有实际用途的额外容器.
//Dictionary declaration
static Dictionary<string, List<string>> sourceList = new Dictionary<string, List<string>>();
//Foreach loop which populates a Dictionary with results from
//a linq query that i need to print out.
foreach (var v in linqQueryResult) {
List<string> answers = v.solution.Select(s => s.Answer).ToList();
sourceList.Add(v.question, answers);
}
//foreach loop to print out contents of Dictionary
foreach (KeyValuePair<string, List<string>> item in sourceList) {
Debug.WriteLine(item.Key);
foreach(string answer in item.Value) {
Debug.WriteLine(answer);
}
}
Run Code Online (Sandbox Code Playgroud)
如果由于其他原因需要课程,那可能如下所示.
(请注意,问题字符串在类中都被引用并在字典中用作键,但字典键实际上并未用于此代码中的任何内容.)
//Class For Storing Question Information
public class QuestionAnswers {
public string Question { get; private set; }
public List<string> Answers { get; private set; }
public QuestionAnswers(string question, IEnumerable<string> answers) {
Question = question;
Answers = new List<string>(answers);
}
}
//Dictionary declaration
static Dictionary<string, QuestionAnswers> sourceList = new Dictionary<string, QuestionAnswers>();
//Foreach loop which populates a Dictionary with results from
//a linq query that i need to print out.
foreach (var v in linqQueryResult) {
QuestionAnswers qa = new QuestionAnswers(v.question, v.solution.Select(s => s.Answer));
sourceList.Add(qa.Question, qa);
}
//foreach loop to print out contents of Dictionary
foreach (QustionAnswers qa in sourceList.Values) {
Debug.WriteLine(qa.Question);
foreach(string answer in qa.Answers) {
Debug.WriteLine(answer);
}
}
Run Code Online (Sandbox Code Playgroud)