有人可以帮我弄清楚这个编译错误
编译错误(第10行,第17行):最佳重载方法匹配 对于 'System.Collections.Generic.Dictionary> .Dictionary(INT)' 有一些无效的参数编译错误(第13行,第5栏): 参数1:无法转换 'System.Collections.Generic.IEnumerable>>' 到'int'上次运行:8:16:27 pm编译:0s执行:0.188s内存:0b CPU:0s
指向我代码的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 :(得分: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>());