好吧,最简单的方法是:
char[] chrArr = string.Join(string.Empty, strArr).ToCharArray();
为了确保这里没有混淆性能特征,这里有一个在LINQPad中测试的简短程序(不要忘记在右下角打开优化):
static string[] strArr = { "123", "456", "789" };
void Main()
{
const int iterations = 10000000; // 10 million
// Warm up JITter
StringJoin();
LINQSelectMany();
LINQ();
Stopwatch sw = Stopwatch.StartNew();
for (int index = 0; index < iterations; index++)
StringJoin();
sw.Stop();
sw.ElapsedMilliseconds.Dump("String.Join");
sw.Restart();
for (int index = 0; index < iterations; index++)
LINQSelectMany();
sw.Stop();
sw.ElapsedMilliseconds.Dump("LINQ SelectMany");
sw.Restart();
for (int index = 0; index < iterations; index++)
LINQ();
sw.Stop();
sw.ElapsedMilliseconds.Dump("LINQ");
}
public static void StringJoin()
{
char[] c = string.Join(string.Empty, strArr).ToCharArray();
}
public static void LINQSelectMany()
{
char[] c = strArr.SelectMany(s => s).ToArray();
}
public static void LINQ()
{
var characters = (from s in strArr
from c in s
select c).ToArray();
}
如果您想使用它,可以在此处下载此 LINQPad 脚本。
输出(以毫秒为单位):
String.Join
765
LINQ SelectMany
5098
LINQ
5465
(关于性能测量代码的常见警告在这里适用,指出我犯的任何错误)