Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading