gpt4 book ai didi

C# Foreach 循环哈希表问题

转载 作者:行者123 更新时间:2023-11-30 19:04:16 25 4
gpt4 key购买 nike

我有一些代码可以填充哈希表,其中问题作为键,答案数组列表作为值。

然后我想从哈希表中打印出这些值,以便它显示哈希表中每个单独问题的问题和相应的解决方案。

我知道我用 foreach 循环做了一些非常愚蠢的事情来打印哈希表的内容,但我已经连续编码了几个小时,我想不出打印嵌套数组列表的逻辑。

非常感谢帮助。

代码如下:

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

最佳答案

当您使用 LINQ 时,您显然不受限于框架 1.1,因此您不应使用 HashTableArrayList 类。您应该改用严格类型化的通用 DictionaryList 类。

您不需要类来保存问题和答案,因为您拥有 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);
}
}

如果您出于其他原因需要该类(class),可能如下所示。

(请注意,问题字符串在类中被引用并用作字典中的键,但字典键在这段代码中并没有真正用于任何事情。)

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

关于C# Foreach 循环哈希表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/815234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com