LINQ: How do I concatenate a list of integers into comma delimited string?

被刻印的时光 ゝ 提交于 2019-12-31 09:09:09

问题


It's probably something silly I missed, but I try to concatenate a list of integers instead of summing them with:

integerArray.Aggregate((accumulator, piece) => accumulator+"," + piece)

The compiler complained about argument error. Is there a slick way to do this without having to go through a loop?


回答1:


Which version of .NET? In 4.0 you can use string.Join(",",integerArray). In 3.5 I would be tempted to just use string.Join(",",Array.ConvertAll(integerArray,i=>i.ToString())); (assuming it is an array). Otherwise, either make it an array, or use StringBuilder.




回答2:


You probably want to use String.Join.

string.Join(",", integerArray.Select(i => i.ToString()).ToArray());

If you're using .Net 4.0, you don't need to go through the hassle of reifying an array. and can just do

 string.Join(",", integerArray);



回答3:


The error you are getting is because you didn't use the override of Aggregate which lets you specify the seed. If you don't specify the seed, it uses the type of the collection.

integerArray.Aggregate("", (accumulator, piece) => accumulator + "," + piece);



回答4:


Just to add another alternative to @Marc's

var list = string.Join( ",", integerArray.Select( i => i.ToString() ).ToArray() );


来源:https://stackoverflow.com/questions/2917571/linq-how-do-i-concatenate-a-list-of-integers-into-comma-delimited-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!