2015-06-23 53 views
2

我搜索了一种方法来拆分字符串,我找到了一个。
现在我的问题是,我不能使用它所描述的方法。C#IEnumerable <string>和字符串[]

Stackoverflow answer

这是要告诉大家,我

不能隐式转换类型 'System.Collections.Generic.IEnumerable' 到 '字符串[]'。

所提供的方法是:

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] 
+0

阵列不实现IEnumerable

+2

@AmitKumarGhosh可以了'字符串[]'分配给IEnumerable的''问题是相反的:自从.NET Framework 2.0以来,您无法将'IEnumerable '分配给'string []' –

+1

@AmitKumarGhosh,[数组执行IEnumerable ](https://ideone.com/d8rBt6)在[运行时](https://msdn.microsoft.com/en-us/library/system.array.aspx#remarksToggle)。但是,正如Dennis_E所提到的,这不是问题的根源。 – soon

回答

8

你必须使用ToArray()方法:

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

您可以隐式转换ArrayIEnumerable但反之亦然。

+0

我现在试了2个多小时,从未想过它那么简单。非常感谢你! – Chakratos

+0

@Chakratos - 很高兴帮助! – Kamo

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; 
    } 
} 
相关问题