2017-04-09 25 views
-2

我正在創建一個程序,將學生和他們的分數存儲在字典列表混合中。例如,我需要用for循環創建新列表C#

Dictionary<int, List<int>> examGrades = new Dictionary<int, List<int>>(); 
List<int> name = new List<int>(); 

有無論如何使用for循環來爲新學生創建新列表嗎? 當我例如

Console.WriteLine("What is the student name"); 
string name = Console.ReadLine(); 
List<int> name = new List<int>(); 

編寫代碼在這種情況下,我會得到一個錯誤的無法創建,因爲「名稱」已經存在。無論如何要解決這個問題呢?這將在嵌套for循環的內循環中。 outer for循環會遍歷並將項添加到當前列表中。任何幫助,將不勝感激。謝謝。

+0

只需調用其他名稱? – TZHX

回答

0

您將添加項目到字典之前必須檢查,如果字典中已經包含了關鍵(學生,在這種情況下)。

使用ContainsKey擴展方法Dictionary,檢查學生名稱是否已存在於字典中。

static void Main(string[] args) 
    { 
     Dictionary<string, List<int>> studentMarks = new Dictionary<string, List<int>>(); 
     string decision = "N"; 
     do 
     { 
      Console.WriteLine("Enter Student Name"); 
      string name = Console.ReadLine(); 

      //If you add the same key to dictionary, exception will be thrown 
      if(studentMarks.ContainsKey(name)) 
      { 
       Console.WriteLine("The student already exists!"); 
       continue; 
      } 

      Console.WriteLine("Enter the marks of " + name); 
      List<int> marks = new List<int>(); 

      int subjectCount = 5; 

      //Loop until your desired count of marks has been entered 
      for (int i = 0; i < subjectCount; i++) 
      { 
       string mark = Console.ReadLine(); 

       if (string.IsNullOrEmpty(mark)) 
       { 
        break; 

       } 

       int markInt = Convert.ToInt32(mark); 
       marks.Add(markInt); 
      } 

      studentMarks.Add(name, marks); 

      Console.WriteLine("Do you want to add details of another student? (Y/N)"); 
      decision = Console.ReadLine(); 
     } 
     //Keep doing until user wants to 
     while (decision == "Y"); 
    } 
+0

非常感謝您的意見,我會在我的代碼中試一試,並告訴您它是如何工作的! –

+0

考慮將我的答案標記爲接受,如果它的工作!謝謝。 –

+0

這確實可以解決問題!隨着調整來適應我的需求它的作品很好,謝謝! –

0

試試這個:

Dictionary<string, List<int>> examGrades = new Dictionary<int, List<int>>(); 
for(int i = 0; i < 10; i++) 
{ 
    Console.Write("Student's name: "); 
    string name = Console.ReadLine(); 
    Console.Write("Student's mark (type 0 at the end): "); 
    List<int> marks = new List<int>(); 
    int mark = 0; 
    do 
    { 
     int mark = Convert.ToInt32(Console.ReadLine()); 
     if(mark == 0) 
      break; 
     marks.Add(mark); 
    } while(true); 
    examGrades.Add(name, marks); 
} 
+0

非常感謝你的這一點,我一定要嘗試一下,並會告訴你它是否適合我的需要!我很感激幫助。 –