C# foreach loop hashtable 문제
문제
키로 질문으로 해시 가능을 채우는 코드가 있고 값으로 답변의 배열 목록이 있습니다.
그런 다음 해시 테이블에서 이러한 값을 해시 테이블의 각 개별 질문에 대한 질문과 해당 솔루션을 표시하도록 해시 테이블에서 이러한 값을 인쇄하고 싶습니다.
나는 Hashtable 내용을 인쇄하기 위해 Foreach 루프로 완전히 어리석은 일을했다는 것을 알고 있지만, 몇 시간을 똑바로 코딩하고 있으며 중첩 된 Arraylist를 인쇄하는 논리를 생각할 수 없습니다.
큰 감사를 표합니다.
코드는 다음과 같습니다.
//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로 제한되지 않으므로 사용하지 않아야합니다. HashTable
그리고 ArrayList
클래스. 엄격하게 입력 한 제네릭을 사용해야합니다 Dictionary
그리고 List
대신 수업.
당신은 당신이 가지고있는 것처럼 질문과 답을 유지하기 위해 수업이 필요하지 않습니다. 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 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);
}
}
다른 팁
이 시도
foreach (DictionaryEntry entry in sourceList)
{
Debug.WriteLine(entry.Key);
foreach (object item in (ArrayList)entry.Value)
{
Debug.WriteLine(item.ToString());
}
}
사소한 조정
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
}
이건 말해서는 안됩니다 :
Debug.WriteLine(sourceList.Values.ToString());
이거?
foreach(var obj in sourceList.Values)
Debug.WriteLine(obj);
첫째, 강력하게 입력 된 일반 컬렉션은 더 쉬워집니다. 강력하게 입력 한 컬렉션의 별칭을 정의하여 시작하겠습니다.
using MyHash = System.Collections.Generic.Dictionary<string,
System.Collections.Generic.List<string>>;
이제부터 Myhash는 긴 일반 정의와 동일하게 의미합니다. 이제 hashtable 멤버를 다음과 같이 선언 할 수 있습니다.
static MyHash sourceList = new MyHash();
그리고 그것을 반복하는 것 :
foreach (var pair in sourceList)
{
var question = pair.Value;
Console.WriteLine(question);
foreach (var answer in pair.Value)
Console.WriteLine(" " + answer);
}
이것이 유용하기를 바랍니다.
foreach (hashtable의 dictionaryentry 항목) {
} 더 많은 것을 찾으십시오 http://www.dotnetperls.com/hashtable