如何在字典中存储数组值?

时间:2013-08-02 11:34:05

标签: asp.net

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

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

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

3 个答案:

答案 0 :(得分:0)

您可以将数组存储在字典中,与任何其他类型的对象相同:

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

dict.Add(1, new int[] { 1, 2, 3});

答案 1 :(得分:0)

如果要将数组转换为字典,可以执行此操作。

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

这会将字符串作为键并将1设置为默认整数(因为它出现了一次)。但是,如果您的words数组包含重复键,则会抛出异常,因为字典不能包含重复键。我没有使用复杂的LINQ查询来处理它,而是建议使用一个简单的循环。

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
}

答案 2 :(得分: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);

并经过测试。

相关问题