C#IEnumerable<;字符串>;和字符串[]
我搜索了一个拆分字符串的方法,找到了一个。C#IEnumerable<;字符串>;和字符串[],c#,arrays,string,split,ienumerable,C#,Arrays,String,Split,Ienumerable,我搜索了一个拆分字符串的方法,找到了一个。 现在我的问题是我不能像上面描述的那样使用这个方法 它会告诉我 无法隐式转换类型 “System.Collections.Generic.IEnumerable”到“string[]” 提供的方法是: public static class EnumerableEx { public static IEnumerable<string> SplitBy(this string str, int chunkLength) {
现在我的问题是我不能像上面描述的那样使用这个方法 它会告诉我 无法隐式转换类型 “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);
}
}
}
您必须使用
ToArray()
方法:
string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat]
您可以将
数组
隐式转换为IEnumerable
,但不能将其转换为IEnumerable 注意,您甚至可以直接修改该方法以返回字符串[]
:
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;
}
}
公共静态类EnumerableEx
{
公共静态字符串[]SplitByToArray(此字符串str,int chunkLength)
{
if(String.IsNullOrEmpty(str))抛出新的ArgumentException();
如果(chunkLength<1)抛出新ArgumentException();
var arr=新字符串[(str.Length+chunkLength-1)/chunkLength];
对于(int i=0,j=0;istr.Length)
chunkLength=str.Length-i;
arr[j]=str.Substring(i,chunkLength);
}
返回arr;
}
}
如果你最终以这种方式结束:
IEnumerable things=new[]{“鲍勃”、“乔”、“猫”}代码>
您可以将其转换为字符串[]
,如下所示:
string[]myStringArray=things.Select(it=>it.ToArray()代码>阵列不实现IEnumerable@AmitKumarGhosh您可以将string[]
分配给IEnumerable
问题恰恰相反:从.NET Framework 2.0开始,您不能将IEnumerable
分配给string[]
@AmitKumarGhosh,但只能在。但是,正如Dennis_E所提到的,这不是问题的根源。@soon:这也是:“从.NET Framework 2.0开始,Array类实现System.Collections.Generic.IList、System.Collections.Generic.ICollection和System.Collections.Generic.IEnumerable通用接口。这些实现在运行时提供给阵列…”当然,我的评论在运行时
单词下也有相同的链接。我现在尝试了2个多小时,从没想到它这么简单。非常感谢!@Chakratos-很高兴它有帮助!
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;
}
}