能否用String.Join仅拼接每个字符串的指定单个字符?(无循环实现)
解决方案
要实现仅拼接每个字符串中指定位置的字符(以第三个字符为例,对应C#字符串的0索引位置2),且避免显式循环,可以借助LINQ的Select方法做投影处理,再用string.Join完成拼接:
List<string> names = new List<string>() { "John", "Anna", "Monica" }; int targetCharIndex = 2; // 对应第三个字符 var result = string.Join("", names.Select(name => name[targetCharIndex])); // 输出结果:"hnn"
补充说明
如果需要处理列表中存在长度不足的字符串(避免索引越界),可以在投影时增加判断逻辑:
var result = string.Join("", names.Select(name => name.Length > targetCharIndex ? name[targetCharIndex] : '\0' // 用默认字符替代,也可换成其他占位符 ));
内容的提问来源于stack exchange,提问作者Yohan Trens
相关产品推荐
相关产品推荐

