c# - 将项目数组的子集放入字符串的最快方法?
问题描述
我的方法接收一个位置数组,这些位置用于连接另一个数组中的一些项目。目前,我正在遍历这些位置并将它们添加到 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(",");
}
有什么更快的吗?
解决方案
尝试:
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]));
推荐阅读
- python - 如何保护烧瓶服务器应用程序中的密码?
- ruby-on-rails - Rails 6 - 使用 Devise(Ruby on Rails)的 API 身份验证
- ios - 在 Swift 中用单词和逗号分隔列表末尾替换最终逗号的有效方法
- r - R package NAMESPACE: 列在一个以上类别中的包
- sql - 如何在 SQL Server 存储过程中拆分和获取逗号分隔的字符串?
- spring - 分区和 JdbcPagingItemReader 没有给出正确的值
- javascript - WCFM 每次添加产品时自动设置或附加类别
- c# - 从 WPF DataGrid 获取信息
- flutter - Flutter Web 是否有任何 Twitter 身份验证?
- asynchronous - 如何在启动异步操作和在循环中等待其结果之间有一个宽限期?