首页 > 解决方案 > 将项目数组的子集放入字符串的最快方法?

问题描述

我的方法接收一个位置数组,这些位置用于连接另一个数组中的一些项目。目前,我正在遍历这些位置并将它们添加到 a StringBuilder,但是有更快的方法吗?C# 是否有一些方法使用本机代码(类似于 Java 的System.arraycopy)来执行更快的“循环”?

基本思路:

int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

StringBuilder concat = new StringBuilder();

for ( int i = 0; i < positions.length; i++ )
{
    concat.Append(values[positions[i]]);
    concat.Append(",");
}

有什么更快的吗?

标签: c#.netperformance

解决方案


尝试:

int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };

var res = string.Join(",", positions.Select(f => values[f]));


推荐阅读