2016-08-24 18 views
-3

辞書のC#コンソールにsomのフライト情報を入力しようとしています。 しかし、私はそれらを私の辞書に追加する方法を知らない。私は飛行番号(私はキーとして飛行番号が欲しい)で保存したい。ここにクラスとホールコードがあります
辞書に追加する

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>が辞書に直接追加したスキップすることができます。

ユーザ入力を解析した直後にが0であるかどうかをチェックし、直ちにループから抜け出すことを検討してください。そうしないと、リスト/ディクショナリーのフライト情報0のフライト情報が表示されます。

関連する問題