【发布时间】:2021-12-30 09:27:23
【问题描述】:
我可能做错了什么,但我正在尝试做this Kata on Codewars
下面是我当前的代码。
public static class Kata
{
public static IEnumerable<T> UniqueInOrder<T>(IEnumerable<T> arr)
{
Type t = typeof(T);
if (t == typeof(string))
return (IEnumerable<T>)String.Join("",arr.Distinct()).AsEnumerable();
return arr.Distinct().ToArray();
}
}
此 kata 的单元测试期望输入“AAAABBBCCDAABBB”返回为“ABCDAB”。
我上面的代码由于这个错误而失败
Expected is <System.String>, actual is <System.Char[6]>
如果我尝试返回一个字符串,我会收到以下错误:error CS0029: Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable<T>'
如果我无法返回字符串(并且 char 数组失败),我如何返回预期的字符串?
谢谢
【问题讨论】:
-
你传递了一个
string,这是一个IEnumerable<char>,而不是IEnumerable<string>,这意味着T是char而不是string,所以你的if (t == typeof(string))返回false。 -
请注意,您不能简单地通过调用
.Distinct()来解决此问题;如果是这样,就没有挑战了。 -
你的返回类型是
IEnumerable<T>,但你断言它是string。 -
另外......没有理由打电话给
ToArray()。它只是浪费内存和cpu。Distinct()方法本身已经完成了您的 IEnumerable 合同。如果调用者实际上想要一个数组(或列表,或其他),让他们做出选择。 -
用老式的方法来做。循环遍历 IEnumerable,如果元素
i与元素i-1相同,则将其丢弃。如果没有,yield return它
标签: c# algorithm ienumerable