我有一个整数列表说
var items = new[] { 1, 2, 3, 4 };
我想将它们转换为字符串列表。原因是我需要设置看起来像
{<- 1 -> , <-2-> ,<-3-> ,<-4-> }
通常我会创建另一个列表,例如
List<string> list = new List<string>();
foreach (int i in items)
{
list.Add("<-" + i + "->");
}
有什么捷径可以达到同样的效果吗?
我有一个整数列表说
var items = new[] { 1, 2, 3, 4 };
我想将它们转换为字符串列表。原因是我需要设置看起来像
{<- 1 -> , <-2-> ,<-3-> ,<-4-> }
通常我会创建另一个列表,例如
List<string> list = new List<string>();
foreach (int i in items)
{
list.Add("<-" + i + "->");
}
有什么捷径可以达到同样的效果吗?
Try
var lst = items.ToList().ConvertAll(x=>x.ToString()).Select(x=>"<-"+ x+"->");
You could use LINQ and more specifically a combination of the .Select() and .ToList() extension methods:
var items = new[] { 1, 2, 3, 4 };
List<string> list = items.Select(i => string.Format("<-{0}->", i)).ToList();
The .Select() extension method projects each integer element to the corresponding string representation and the .ToList() extension method casts the result to a List<string>.