Home > OS >  Append a string at the start of each element in C#
Append a string at the start of each element in C#

Time:07-21

I have a list of strings

List<string> strings = new List<string>() { "MyItem1", "MyItem2", "MyItem3" };

How do I append "Thisis" at the start of each element in the list so that the new list becomes

List<string> strings = new List<string>() { "ThisisMyItem1", "ThisisMyItem2", "ThisisMyItem3" };

CodePudding user response:

To create a new list you can use Linq:

using System.Linq;

...

List<string> newStrings = strings
  .Select(item => $"Thisis{item}")
  .ToList();

or create and loop:

List<string> newStrings = new List<string>(strings.Count);

foreach (var item in strings)
  newStrings.Add($"Thisis{item}") 

If you want to modify existing strings, just loop:

for (int i = 0; i < strings.Count;   i)
  strings[i] = $"Thisis{strings[i]}";

CodePudding user response:

You can use .Select() to project a collection into a new collection, modifying each element in that projection. Something as simple as:

var modifiedStrings = strings.Select(s => $"Thisis{s}");

Note that this will create an IEnumerable<string>. If you need it to be a List<string> (that is, if you specifically need it to have the features of a List<> such as accessing elements by index) then you can append .ToList() onto any IEnumerable<>:

var modifiedStrings = strings.Select(s => $"Thisis{s}").ToList();
  • Related