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

C# IEnumerable<string> and string[]

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

Whosebug answer

它会告诉我

cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to '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]

你必须使用ToArray()方法:

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

您可以将 Array 隐式转换为 IEnumerable,但不能反过来。

请注意,您甚至可以直接将方法修改为 return a 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();