Appending characters to a List string

百般思念 提交于 2019-12-09 16:53:38

问题


I have an optional custom prefix and suffix in my application, that I want to add to each of the items in my string List. I have tried all of the following and none are working. Can someone point me in the right direction please?

List<string> myList = new List<string>{ "dog", "cat", "pig", "bird" };

string prefix = "my ";
string suffix = " sucks!";

StringBuilder sb = new StringBuilder();
sb.Append(suffix);
sb.Insert(0, prefix);
MyList = sb.ToString();  //This gives me red squigglies under sb.ToString();

I also tried:

myList = myList.Join(x => prefix + x + suffix).ToList();  //Red squigglies

and:

sortBox1.Join(prefix + sortBox1 + suffix).ToList();  //Red squigglies

Where am I going wrong here?


回答1:


It's not really clear why you're using a StringBuilder at all here, or why you'd be trying to do a join. It sounds like you want:

var suckingList = myList.Select(x => "my " + x + " sucks")
                        .ToList();

This is the absolutely normal way of performing a projection to each item in a list using LINQ.




回答2:


List<string> myList = new List<string>{ "dog", "cat", "pig", "bird" };
List<string> myNewList = new List<string>();

string prefix = "my ";
string suffix = " sucks!";

foreach(string s in myList)
{
     myNewList.Add(string.Format("{0}{1}{2}", prefix, s, suffix);
}

myNewList now contains the correct data.



来源:https://stackoverflow.com/questions/13932001/appending-characters-to-a-list-string

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