Home > Net >  How do I replace a specific element in a list
How do I replace a specific element in a list

Time:10-08

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?

CodePudding user response:

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);

CodePudding user response:

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();
  • Related