Problema Hashtable del ciclo Foreach C #
Domanda
Ho del codice che popola una tabella hash con una domanda come chiave e un arraylist di risposte come valore.
Voglio quindi stampare questi valori dalla tabella hash in modo che visualizzi la domanda e le soluzioni corrispondenti per ogni singola domanda nella tabella hash.
So di aver fatto qualcosa di totalmente stupido con il ciclo foreach per stampare i contenuti hashtable, ma sto programmando per alcune ore consecutive e non riesco a pensare alla logica per stampare il mio arraylist annidato.
Aiuto molto apprezzato.
Ecco il codice:
//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());
}
}
Soluzione
Dato che stai usando LINQ non sei ovviamente vincolato al framework 1.1, quindi non dovresti usare le classi HashTable
e ArrayList
. Dovresti usare invece le classi generiche Dizionario
e Elenco
genericamente tipizzate.
Non hai bisogno di una classe per mantenere la domanda e le risposte in quanto hai il Dizionario
. La classe sarebbe solo un contenitore extra senza uno scopo reale.
//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);
}
}
Se hai bisogno della classe per qualche altro motivo, potrebbe apparire come di seguito.
(Nota che la stringa di domanda è sia referenziata nella classe sia usata come chiave nel dizionario, ma la chiave del dizionario non è realmente usata per nulla in questo codice.)
//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);
}
}
Altri suggerimenti
Prova questo
foreach (DictionaryEntry entry in sourceList)
{
Debug.WriteLine(entry.Key);
foreach (object item in (ArrayList)entry.Value)
{
Debug.WriteLine(item.ToString());
}
}
Modifiche minori
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
}
Non dovrebbe essere questo:
Debug.WriteLine(sourceList.Values.ToString());
essere questo?
foreach(var obj in sourceList.Values)
Debug.WriteLine(obj);
In primo luogo, una raccolta generica fortemente tipizzata renderebbe più semplice. Cominciamo definendo un alias per la raccolta fortemente tipizzata:
using MyHash = System.Collections.Generic.Dictionary<string,
System.Collections.Generic.List<string>>;
D'ora in poi, MyHash ha lo stesso significato della lunga definizione generica. Ora puoi dichiarare il membro hashtable come:
static MyHash sourceList = new MyHash();
E itera su di esso come:
foreach (var pair in sourceList)
{
var question = pair.Value;
Console.WriteLine(question);
foreach (var answer in pair.Value)
Console.WriteLine(" " + answer);
}
Spero che sia utile.
foreach (voce DictionaryEntry in Hashtable) {
} Scopri di più in http://www.dotnetperls.com/hashtable