Pull out the value using the key in the dictionary

with my code i have a problem to pull out the value which is the number of words using the key, the word it self is my code,

 public static void essintial(string UserCorpus, string word)
    {
       // string str = "Alameer Ashraf Hassan Alameer ashraf,elnagar.";

        string[] CorpusResult = UserCorpus.Split(' ', ',', '.');

       //Creating the Dictionary to hold up each word as key & its occurance as Value  ......! 
        Dictionary<string, int> Dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

       //looping over the corpus and fill the dictionary in .........!
        foreach (string item in CorpusResult)
        {
            if (item != "")
            {
                if (Dict.ContainsKey(item) == false)
                {
                    Dict.Add(item, 1);
                }
                else
                {
                    Dict[item]++;
                }
            }
        }

        //Console.WriteLine(Dict);
        foreach (var item in Dict)
        {
            Console.WriteLine(item);
        }


        int ss = Dict[word];
        Console.WriteLine(ss);
}

There is a problem to exit the key.

+4
source share
2 answers

I do not know what the problem is that you have, but I have an idea. One of the questions may be the word you provide is not in the dictionary. This may result in KeyNotFoundException. A simple fix would look something like this:

if(Dict.ContainsKey(word)){
    Console.WriteLine(Dict[word]);
} else {
    Console.WriteLine(0); //Or whatever you deem appropriate
}

, , , foreach(var item in Dict). . item KeyValuePair<string,int> Console.WriteLine(item);, , , . Console.WriteLine(item) Console.WriteLine(item.Key + " " +item.Value);

+3

:

string str = "Alameer Ashraf Hassan Alameer ashraf,elnagar.";

        string[] CorpusResult = str.Split(' ', ',', '.');

       //Creating the Dictionary to hold up each word as key & its occurance as Value  ......! 
        Dictionary<string, int> Dict = new Dictionary<string, int>();

       //loopnig over the corpus and fill the dictionary in .........!
        foreach (string item in CorpusResult)
        {
            if (string.IsNullOrEmpty(item)) continue;

            if (Dict.ContainsKey(item))
            {
                Dict[item]++;
            }
            else
            {
                Dict.Add(item, 1);
            }
        }

        Console.WriteLine("Method 1: ");
        foreach (var item in Dict)
        {
            Console.WriteLine(item.Value);
        }

        Console.WriteLine("Method 2: ");
        foreach(var k in Dict.Keys)
        {
            Console.WriteLine(Dict[k]);
        }

.NET Fiddle: https://dotnetfiddle.net/JZ9Eid

+1

Source: https://habr.com/ru/post/1615524/


All Articles