簡體   English   中英

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

[英]C# IEnumerable<string> and string[]

我搜索了一個分割字符串的方法,我找到了一個。
現在我的問題是我無法使用它描述的方法。

Stackoverflow的答案

它會告訴我

不能隱式地將類型'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]

你必須使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM