简体   繁体   English

C#Foreach循环哈希表问题

[英]C# Foreach Loop Hashtable Issue

I have some code which populates a hashtable with a question as the key and an arraylist of answers as the value. 我有一些代码填充哈希表,其中一个问题作为键,一个答案的arraylist作为值。

I want to then print out these values from the hashtable so that it displays the question and corresponding solutions for each individual question in the hashtable. 我想从哈希表中打印出这些值,以便在哈希表中显示每个问题的问题和相应的解决方案。

I know I have done something totally stupid with the foreach loop to printout the hashtable contents, but i've been coding for a good few hours straight and I can't think of the logic to printout my nested arraylist. 我知道我已经用foreach循环做了一些完全愚蠢的事情来打印出哈希表的内容,但是我已经编写了好几个小时的编码,我想不出打印我的嵌套arraylist的逻辑。

Help appreciated greatly. 非常感谢。

Here is the code: 这是代码:

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

As you are using LINQ you are obviously not constrained to framework 1.1, so you should not be using the HashTable and ArrayList classes. 当您使用LINQ时,您显然不受框架1.1的限制,因此您不应该使用HashTableArrayList类。 You should use the strictly typed generic Dictionary and List classes instead. 您应该使用严格类型的通用DictionaryList类。

You don't need a class to keep the question and answers in as you have the Dictionary . 你不需要一个课来保持问题和答案,因为你有Dictionary The class would only be an extra container with no real purpose. 该类只是一个没有实际用途的额外容器。

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

If you need the class for some other reason, that could look like below. 如果由于其他原因需要课程,那可能如下所示。

(Note that the question string is both referenced in the class and used as key in the dictionary, but the dictionary key isn't really used for anything in this code.) (请注意,问题字符串在类中都被引用并在字典中用作键,但字典键实际上并未用于此代码中的任何内容。)

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

Try this 尝试这个

foreach (DictionaryEntry entry in sourceList)
            {
                Debug.WriteLine(entry.Key);
                foreach (object item in (ArrayList)entry.Value)
                {
                    Debug.WriteLine(item.ToString());
                }

            }

Minor tweaks 小调整

foreach (string key in sourceList.Keys)
{
  Console.WriteLine(key);
  foreach(string value in sourceList[key])
  {
    Console.WriteLine("\t{0}", value);  // tab in answers one level
  }
  Console.WriteLine(); // separator between each set of q-n-a
}

foreach (DictionaryEntry entry in Hashtable) { foreach(Hashtable中的DictionaryEntry条目){

} Find more in http://www.dotnetperls.com/hashtable http://www.dotnetperls.com/hashtable中查找更多信息

Shouldn't this: 不应该这样:

Debug.WriteLine(sourceList.Values.ToString());

be this? 是吗?

foreach(var obj in sourceList.Values)
    Debug.WriteLine(obj);

First, a strongly typed generic collection would make it easier. 首先,强类型泛型集合会使其更容易。 Let's start by defining an alias for the strongly typed collection: 让我们首先为强类型集合定义一个别名:

using MyHash = System.Collections.Generic.Dictionary<string,
    System.Collections.Generic.List<string>>;

From now on, MyHash means the same as the lengthy generic definition. 从现在开始,MyHash意味着与冗长的通用定义相同。 Now you can declare the hashtable member like: 现在您可以声明哈希表成员,如:

static MyHash sourceList = new MyHash();

And iterate over it like: 并迭代它像:

foreach (var pair in sourceList)
{
    var question = pair.Value;
    Console.WriteLine(question);
    foreach (var answer in pair.Value)
        Console.WriteLine("    " + answer);
}

Hope this is useful. 希望这很有用。

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

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