C#IEnumerable<;字符串>;和字符串[]

本文关键字:字符串 gt C#IEnumerable lt | 更新日期: 2023-09-27 17:59:03

我搜索了一个拆分字符串的方法,找到了一个
现在我的问题是我不能像上面描述的那样使用这个方法。

堆栈溢出应答

它将告诉我

无法隐式转换类型’系统。集合。通用的IEnumerable"到"string[]"。

提供的方法是:

public static class EnumerableEx
{
    public static IEnumerable<string> SplitBy(this string str, int chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        if (chunkLength < 1) throw new ArgumentException();
        for (int i = 0; i < str.Length; i += chunkLength)
        {
            if (chunkLength + i > str.Length)
                chunkLength = str.Length - i;
            yield return str.Substring(i, chunkLength);
        }
    }
}

他说它是如何使用的:

string[] result = "bobjoecat".SplitBy(3); // [bob, joe, cat]

C#IEnumerable<;字符串>;和字符串[]

您必须使用ToArray()方法:

string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat]

您可以隐式地将Array转换为IEnumerable,但不能反之亦然。

注意,您甚至可以直接修改该方法以返回string[]:

public static class EnumerableEx
{
    public static string[] SplitByToArray(this string str, int chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        if (chunkLength < 1) throw new ArgumentException();
        var arr = new string[(str.Length + chunkLength - 1) / chunkLength];
        for (int i = 0, j = 0; i < str.Length; i += chunkLength, j++)
        {
            if (chunkLength + i > str.Length)
                chunkLength = str.Length - i;
            arr[j] = str.Substring(i, chunkLength);
        }
        return arr;
    }
}

如果以某种方式出现以下情况:IEnumerable<string> things = new[] { "bob", "joe", "cat" };您可以将其转换为string[],如下所示:string[] myStringArray = things.Select(it => it).ToArray();