Home > Software engineering >  Read and write dictionary values c#
Read and write dictionary values c#

Time:07-27

I need help. These are the instructions:

Please add a new value, the key of which is your name, and the value of which is your age. Do this using the Add method.

Next, add another value to the dictionary using the index notation. This time, use a different name and a different age.

Lastly, read the first item you added to the dictionary, and write it to the console using Console.WriteLine.

The last step is the one that I am missing. I cannot figure out how to print the first element in my collection. I get "cannot convert from 'int' to 'string'"

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary<string, int> people = new Dictionary<string, int>();

        people.Add("John Doe", 23);
        people["John Foe"] = 27;  
        
        Console.WriteLine(people[0]);
    }
}

CodePudding user response:

Please note, that Dictionary doesn't have 1st or 2nd items, the order is not guaranteed. Technically you can use Linq and put

using System.Linq;

...
// Get values and return the 1st item whatever it is
Console.WriteLine(people.Values.ElementAt(0));

but there's no guarantee that you'll get 23. I think that you should read "first item you added to the dictionary" as "the key you have added at the very beginning"

// You've started the exercise with "John Doe" 
Console.WriteLine(people["John Doe"]);

CodePudding user response:

As I understand your question, you need the first item of the Dictionary. You can do it just like this

using System.Linq;

Console.WriteLine(people.First());

//or 

Console.WriteLine(people.ToArray()[1]); //the second element

if you need John Doe age

Console.WriteLine(people["John Doe"]); //23

CodePudding user response:

Hope this will help you as you are trying to get information that you have inserted in the dictionary at first.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp5
{    
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> people = new Dictionary<string, int>();

            people.Add("John Doe", 23);
            people["John Foe"] = 27;

            //To get the first inserted pair in the dictionary
            Console.WriteLine(people.First());

            //To get the Key from the first inserted pair in the dictionary
            Console.WriteLine(people.ToList()[0].Key);

            //To get the Age from the first inserted pair in the dictionary
            Console.WriteLine(people.ToList()[0].Value);
        }
    }
}
  • Related