2017-01-28 43 views
0

有人可以幫我找出這個編譯錯誤的最佳重載方法匹配 'System.Collections.Generic.Dictionary <INT,System.Collections.Generic.Dictionary <string,int>> .Dictionary(INT)'

編譯錯誤(第10行,第17列):最佳重載方法匹配 for 'System.Collections.Generic.Dictionary> .Dictionary(int)' 有一些無效參數編譯錯誤(第13行,第5列): 參數1:無法從 'System.Collections.Generic.IEnumerable >>' 轉換爲'int'上次運行:8:16:27 pm編譯:0s執行:0.188s內存:0B CPU:0

是指向我的代碼Enumerable.Range(1,21)部分

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
class Solution 
{ 
    static void Main(String[] args) 
    { 
     int N = Int32.Parse(Console.ReadLine()); 
     var counter = new Dictionary<int, Dictionary<string, int>> 
      (
       Enumerable.Range(1,21) 
       .Select(i => new KeyValuePair<int, Dictionary<string, int>>(i, new Dictionary<string, int>())) 
      ); 
     for(int i = 0; i < N; ++i) 
     { 
      string[] input = Console.ReadLine().Split(' '); 
      switch(input[0]) 
      { 
       case "add":     
        for(int j = 1; j < input[1].Length; ++j) 
        { 
         string sub = input[1].Substring(0,j); 
         if(counter[j].ContainsKey(sub)) 
          counter[j][sub] += 1; 
         else 
          counter[j][sub] = 1; 
        } 
        break; 
       case "find": 
        Console.WriteLine 
        (
         counter[input[1].Length].ContainsKey(input[1]) 
         ? counter[input[1].Length][input[1]] 
         : 0 
        ); 
        break; 
       default: 
        break; 
      } 
     } 
    } 
} 

我想初始化的鍵值對的字典

[1] = new Dictionary<string,int>(), 
[2] = new Dictionary<string,int>(), 
. 
. 
. 
[21] = new Dictionary<string,int>() 

此外,我很好奇C#是否具有更好的數據結構,以便通過快速查找子字符串來保存字符串集合(針對此問題https://www.hackerrank.com/challenges/contacts)。

+0

可以使用'Enumerable.Range(1,21).ToDictionary(T => T,新詞典());' – Saravanan

+0

@Saravanan甲小的修正中所共享的代碼。它應該是'var counter = Enumerable.Range(1,21).ToDictionary(t => t,t => new Dictionary ());' –

+0

@ChetanRanpariya:明白了:) – Saravanan

回答

2

Dictionary的參數化構造函數需要「int」的第一個參數和「IEqualityComparor」類型的第二個參數。

https://msdn.microsoft.com/en-us/library/6918612z(v=vs.110).aspx

這些都不是正確傳遞作爲你的代碼的一部分。

可以簡化

var counter = new Dictionary<int, Dictionary<string, int>>(); 
foreach (var i in Enumerable.Range(1,21)) 
{ 
    counter.Add(i, new Dictionary<string, int>()); 
} 

也由Saravanan在評論中提到,您可以使用下面的行,甚至簡單的代碼。

var counter = Enumerable.Range(1, 21).ToDictionary(t => t, t => new Dictionary<string, int>()); 
相關問題