-3
char[] delimiterChars = { ' ', ',', '.', ':', '/', '-', '\t', '=', '&', '?' };

string Str = Convert.ToString(entry.Value);

string[] words = Str.Split(delimiterChars);
4

3 回答 3

0

If you want to convert an array to a dictionary, you can do this.

Dictionary<string, int> wordsDict = words.ToDictionary(x => x, x => 1);

This will put the string as the key and set 1 as the default integer (because it has appeared once). However, if your words array contains duplicate keys, it'll throw an exception because a dictionary can't contain duplicate keys. Instead of having a convoluted LINQ query to handle that, I suggest using a simple loop.

Dictionary<string, int> wordsDict = new Dictionary<string,int>();

foreach (string word in words)
{ 
    if(wordsDict.ContainsKey(word)) //if the word already exists
       wordsDict[word]++; //increment the value by 1
    else
       wordsDict.Add(word, 1); //otherwise add the word to the dictionary
}
于 2013-08-02T12:00:11.997 回答
0

我的解决方案(最后几分钟写的):

char[] delimiterChars = { ' ', ',', '.', ':', '/', '-', '\t', '=', '&', '?' };
Dictionary<string, int> result = new Dictionary<string,int>();

List<string> urlList = new List<string>();
urlList.Add("test test test");

foreach (string url in urlList)
{
  var wordList = url.Split(delimiterChars);
  foreach (string word in wordList)
  {
    if (!result.ContainsKey(word))
    {
      result.Add(word, 1);
    }
    else
    {
      result[word]++;
    }
  }
}
Console.WriteLine(result.Count);

并经过测试。

于 2013-08-02T12:09:24.617 回答
0

您可以将数组存储在字典中,就像任何其他类型的对象一样:

var dict = new Dictionary<int, int[]>();

dict.Add(1, new int[] { 1, 2, 3});
于 2013-08-02T11:36:39.830 回答