无法隐式转换类型' int'到&char;#39;在使用聚合扩展方法时 [英] Cannot implicitly convert type 'int' to 'char' while using Aggregate Extension method
问题描述
尝试反转字符串,但在聚合函数中出现错误
Trying to reverse a string but getting error in Aggregate function
private string Reverse(string strValue)
{
char[] chArray = strValue.ToCharArray();
var reverse = chArray.Reverse();
var res = reverse.Aggregate((a,b)=>a+b);
return res.ToString();
}
无法将类型'int'隐式转换为'char'.存在显式转换(您是否缺少演员表?)那怎么了?
推荐答案
确切地说: a + b
的结果是 int
,但是您需要成为 char
.要使其编译,您可以使用:
Exactly as it says: the result of a + b
is an int
, but you want it to be a char
. To get it to compile you can just use:
var res = reverse.Aggregate((a,b)=>(char) (a+b));
...但是我认为这不会满足您的要求.
... but I don't think that will do what you want it to.
我建议您不要以LINQ开头:
I suggest you don't use LINQ for this to start with:
private string Reverse(string strValue)
{
char[] chArray = strValue.ToCharArray();
Array.Reverse(chArray);
return new string(chArray);
}
请注意,此不能正常使用,例如组合字符,代理对等.
Note that this doesn't work properly with things like combining characters, surrogate pairs etc.
如果您真的想使用LINQ,可以使用:
If you really wanted to use LINQ, you could do it with:
private string Reverse(string strValue)
{
return new string(strValue.Reverse().ToArray());
}
无需调用 Aggregate
.如果您真的想要使其变慢并且将字符串连接与 Aggregate
(它将是O(n 2 ))一起使用,则可以执行此操作像这样:
There's no need to call Aggregate
. If you really want to make it slow and use string concatenation with Aggregate
(it'll be O(n2)) you can do it like this:
private string Reverse(string strValue)
{
return strValue.Reverse().Aggregate("", (str, c) => str + c);
}
这里我们提供了一个字符串种子值,因此参数 str
将是字符串,而 +
将是字符串串联,而不是字符 addition .
Here's we've provided a string seed value, so the parameter str
will be a string and +
will be string concatenation, not character addition.
您可以使用 StringBuilder
使其更高效:
You can make it more efficient using StringBuilder
:
private string Reverse(string strValue)
{
return strValue.Reverse()
.Aggregate(new StringBuilder(), (sb, c) => sb.Append(c))
.ToString();
}
...但是我仍然不确定是否值得...
... but I'm still not sure it's worth it...
这篇关于无法隐式转换类型' int'到&char;#39;在使用聚合扩展方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!