Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c# - Extract key value pair from dictionary

I'm at the first step in programming and i'm stuck with a problem with Dictionary(key value) pair. The statement of the problem is:

Write a console application that extracts and prints the key and value on a line. Example: For input data: year:2018

The console will display:

year

2018

here is my code:

        string inputData = Console.ReadLine();
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        dictionary.Add(inputData, 2018 );

        foreach (KeyValuePair<string, int> kvp in dictionary)
        {
            Console.WriteLine("{0}
{1}", kvp.Key, kvp.Value);
        }
question from:https://stackoverflow.com/questions/65617458/extract-key-value-pair-from-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// expects year:2018
var inputData = Console.ReadLine();

// split by ':' to get 'year' and '2018' values
var values = inputData.Split(':');

// creates a dictionary
var dictionary = new Dictionary<string, int>();

// add the 'year' string as key and '2018' as value
dictionary.Add(values[0], Convert.ToInt32(values[1]));

// print all the dictionary
foreach (var kvp in dictionary)
{
    Console.WriteLine("{0}
{1}", kvp.Key, kvp.Value);
}

However, the problem description is not asking you to use a dictionary. So, instead of creating a dictionary, you can simply print the values.

var inputData = Console.ReadLine();
var values = inputData.Split(':');
Console.WriteLine(values[0]);
Console.WriteLine(values[1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...