C# Foreach 循环哈希表问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/815234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:16:42  来源:igfitidea点击:

C# Foreach Loop Hashtable Issue

c#hashtableforeach

提问by Goober

I have some code which populates a hashtable with a question as the key and an arraylist of answers as the value.

我有一些代码用一个问题作为键和一个答案数组作为值填充一个哈希表。

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 循环做了一些非常愚蠢的事情来打印哈希表内容,但我已经连续编码了几个小时,我想不出打印我嵌套数组列表的逻辑。

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

采纳答案by Guffa

As you are using LINQ you are obviously not constrained to framework 1.1, so you should not be using the HashTableand ArrayListclasses. You should use the strictly typed generic Dictionaryand Listclasses instead.

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

You don't need a class to keep the question and answers in as you have the Dictionary. The class would only be an extra container with no real purpose.

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

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

回答by Nathan Ridley

Shouldn't this:

这不应该:

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

be this?

是这个?

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

回答by Gary

Try this

尝试这个

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

            }

回答by Gishu

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
}

回答by Andomar

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. Now you can declare the hashtable member like:

从现在开始,MyHash 的含义与冗长的泛型定义相同。现在您可以像这样声明哈希表成员:

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.

希望这是有用的。

回答by Vijayakumar G.

foreach (DictionaryEntry entry in Hashtable) {

foreach(哈希表中的 DictionaryEntry 条目){

} Find more in http://www.dotnetperls.com/hashtable

http://www.dotnetperls.com/hashtable 中查找更多信息