Pregunta

Tengo un código que llena una tabla hash con una pregunta como clave y un arraylist de respuestas como valor.

Quiero imprimir estos valores desde la tabla hash para que muestre la pregunta y las soluciones correspondientes para cada pregunta individual en la tabla hash.

Sé que he hecho algo totalmente estúpido con el bucle foreach para imprimir el contenido de la tabla hash, pero he estado programando durante unas cuantas horas seguidas y no puedo pensar en la lógica para imprimir mi arraylist anidado.

Ayuda muy apreciada.

Aquí está el código:

//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());
            }
        }
¿Fue útil?

Solución

Como está usando LINQ, obviamente no está limitado al marco 1.1, por lo que no debe usar las clases HashTable y ArrayList . En su lugar, debe utilizar las clases Dictionary y List de forma estricta.

No necesita una clase para mantener la pregunta y las respuestas ya que tiene el Diccionario . La clase solo sería un contenedor adicional sin un propósito real.

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

Si necesita la clase por alguna otra razón, podría verse a continuación.

(Tenga en cuenta que la cadena de la pregunta está referenciada en la clase y utilizada como clave en el diccionario, pero la clave del diccionario no se usa realmente para nada en este código).

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

Otros consejos

Prueba esto

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

            }

Ajustes menores

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
}

No debería esto:

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

sea esto?

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

Primero, una colección genérica fuertemente tipificada lo haría más fácil. Comencemos por definir un alias para la colección fuertemente tipada:

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

De ahora en adelante, MyHash significa lo mismo que la definición genérica extensa. Ahora puede declarar el miembro de la tabla hash como:

static MyHash sourceList = new MyHash();

Y iterar sobre él como:

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

Espero que esto sea útil.

foreach (entrada de DictionaryEntry en Hashtable) {

}  Encuentre más en http://www.dotnetperls.com/hashtable

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top