C#IEnumerable 和字符串[]

问题描述 投票:2回答:3

我搜索了一个分割字符串的方法,我找到了一个。 现在我的问题是我无法使用它描述的方法。

Stackoverflow answer

它会告诉我

不能隐式地将类型'System.Collections.Generic.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# arrays string split ienumerable
3个回答
8
投票

你必须使用ToArray()方法:

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

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


1
投票

请注意,您甚至可以直接修改方法以返回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;
    }
}

0
投票

如果不知何故你最终得到这个:IEnumerable<string> things = new[] { "bob", "joe", "cat" };你可以把它变成像这样的string[]string[] myStringArray = things.Select(it => it).ToArray();

© www.soinside.com 2019 - 2024. All rights reserved.