2016-08-24 171 views
-3

我試圖輸入som飛行信息到詞典C#控制檯。 但我不知道如何將這些添加到我的Dictionary.I想要按航班號存儲(我想將航班號作爲KEY)。這裏是我的課程和洞代碼
添加到詞典

public class Flight 
    { 
     public int FlightNr; 
     public string Destination; 
    } 

     int FlNr; 
     string FlDest; 
     List<Flight> flightList = new List<Flight>(); 

     do 
     { 

      Console.Write("Enter flight nummer (only numbers) :"); 
      FlNr = int.Parse(Console.ReadLine()); 

      Console.Write("Enter destination :"); 
      FlDest = Console.ReadLine(); 

      flightList.Add(new Flight() { FlightNr = FlNr, Destination = FlDest }); 


     } while (FlNr != 0); 

     // create Dictionary 
     Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>(); 

     // My question is How to add those flights in my Dictionary ? 

     dictioneryFlight.Add(I don't know what to input here); 

或者是我的其他代碼有問題嗎?我錯過了什麼?先謝謝你!

+1

你要使用的關鍵是什麼字典?航班號?你需要指定。 – itsme86

+0

@ itsme86是航班號,謝謝 –

回答

2

如果你想使用的按鍵的號碼爲你的字典,那麼你不需要飛行的名單,但你可以直接使用

Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>(); 
    do 
    { 

     Console.Write("Enter flight nummer (only numbers) :"); 
     // Always check user input, do not take for granted that this is an integer    
     if(Int32.TryParse(Console.ReadLine(), out FlNr)) 
     { 
      if(FlNr != 0) 
      { 
       // You cannot add two identical keys to the dictionary 
       if(dictioneryFlight.ContainsKey(FlNr)) 
        Console.WriteLine("Fly number already inserted"); 
       else 
       { 
        Console.Write("Enter destination :"); 
        FlDest = Console.ReadLine(); 

        Flight f = new Flight() { FlightNr = FlNr, Destination = FlDest }; 
        // Add it 
        dictioneryFlight.Add(FlNr, f); 
       } 
      } 
     } 
     else 
      // This is needed to continue the loop if the user don't type a 
      // number because when tryparse cannot convert to an integer it 
      // sets the out parameter to 0. 
      FlNr = -1; 

    } while (FlNr != 0); 
+0

+1地址添加了錯誤添加的航班0,並防止添加重複的航班信息。 – itsme86

0

沒有絕對的把握,但我認爲你的意思是按航班號像

//declare this before your loop starts 
    Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>(); 

    //Add to dictionary in your loop 
    dictioneryFlight.Add(FlNr, new Flight() { FlightNr = FlNr, Destination = FlDest }); 
1

存儲如果你想創建一個字典出機票的列表,你可以使用ToDictionary()

var dict = flightList.ToDictionary(f => f.FlightNr); 

你可以不用LINQ像這樣:

var dict = new Dictionary<int, Flight>(); 
foreach (var flight in flightList) 
    dict.Add(flight.FlightNr, flight); 

正如其他人所說,你可以跳過有List<Flight>完全和正在創建的,而不是當他們只需直接添加到字典中。

你可能要考慮的一件事是在解析用戶輸入之後立即檢查FlNr是否爲0,如果是,則立即跳出循環。否則,您的列表/字典中將顯示航班號爲0的航班信息。