最短方法将数组转换为字符串在C#/ LINQ [英] Shortest method to convert an array to a string in c#/LINQ
本文介绍了最短方法将数组转换为字符串在C#/ LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为封闭的这个问题。
我有元件的阵列/列表。我想将其转换为字符串,通过自定义delimitator分开。例如:
[1,2,3,4,5] => 1,2,3,4,5
什么是在C#中做到这一点的最短/ esiest方式?
我一直通过循环列表,检查如果当前元素是不添加分离器之前的最后一个完成此
的for(int i = 0; I< arr.Length ++ I)
{
STR + =改编[I]的ToString();
如果(ⅰ&下; arr.Length)
STR + =;
}
有一个LINQ的功能,可以帮助我少写code?
解决方案
的string.join(,arr.Select(P =方式> p.ToString())的ToArray ())
Closed as exact duplicate of this question.
I have an array/list of elements. I want to convert it to a string, separated by a custom delimitator. For example:
[1,2,3,4,5] => "1,2,3,4,5"
What's the shortest/esiest way to do this in c#?
I have always done this by cycling the list and checking if the current element is not the last one before adding the separator.
for(int i=0; i<arr.Length; ++i)
{
str += arr[i].ToString();
if(i<arr.Length)
str += ",";
}
Is there a LINQ function that can help me write less code?
解决方案
String.Join(",", arr.Select(p=>p.ToString()).ToArray())
这篇关于最短方法将数组转换为字符串在C#/ LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文