添加到词典

时间:2016-08-24 20:03:55

标签: c# dictionary

我正在尝试将som航班信息输入到Dictionary C#console。 但我不知道如何将这些添加到我的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);

或者我的其他代码出了什么问题?我错过了什么?先感谢您!

3 个答案:

答案 0 :(得分: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); 

答案 1 :(得分: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的航班信息。

答案 2 :(得分: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 });