简体   繁体   English

如何替换列表中的特定元素

[英]How do I replace a specific element in a list

Let's say I want to replace the element IOES with the element Android .假设我想用元素IOES替换元素Android

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

How do I do it?我该怎么做?

If you want to replace whole words only (say IOS , but not BIOS ) you can try regular expressions :如果你只想替换整个单词(比如IOS ,而不是BIOS )你可以尝试正则表达式

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>你可以使用Linq

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

...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM