2016-08-24 204 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的航班信息。