用字典里的一个键算出这个值

本文关键字:一个 字典 | 更新日期: 2023-09-27 18:21:45

在我的代码中,我无法通过使用关键字(单词it self)来获取单词的值那是我的代码,

 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);
}

取出钥匙有问题。

用字典里的一个键算出这个值

我不知道你到底有什么问题,但我有一个主意。一个问题可能是你提供的单词不在字典里。这可能会导致KeyNotFoundException。一个简单的修复方法是:

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.Key + " " +item.Value); 替换Console.WriteLine(item)

试试这个:

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