Martin Slavchev
Martin Slavchev

Reputation: 13

How do I replace a specific element in a list

Let's say I want to replace the element IOES with the element Android.

string input = "IOES Windows Linux";
List<string> os = input.Split(" ").ToList();

How do I do it?

Upvotes: 0

Views: 55

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

If you want to replace whole words only (say IOS, but not BIOS) you can try regular expressions:

string result = Regex.Replace(input, "\bIOES\b", "Android");

In general case, you may want to escape some characters:

string toFind = "IOES";
strung toSet = "Android";

string result = Regex.Replace(
  input, 
  @"\b" + Regex.Escape(toFind) + @"\b", 
  toSet);

If you insist on List<string> you can use Linq:

List<string> os = input
  .Split(' ')
  .Select(item => item == "IOES" ? "Android" : item)
  .ToList();

...

string result = string.Join(" ", os);

Upvotes: 1

StriplingWarrior
StriplingWarrior

Reputation: 156748

There are many ways. One I'd consider is to create a simple transformation like this:

string input = "IOES Windows Linux";
List<string> os = input.Split(" ")
    .Select(os => os switch { 
        "IOES" => "Android", 
        _ => os 
        })
    .ToList();

Upvotes: 1

Related Questions