抱歉,您必须循环播放。没有办法绕过它。
此外,所有其他答案都会为您提供一个包含所需元素的 新数组。如果您希望 same array 修改其元素,正如您的问题所暗示的那样,您应该这样做。
for (int index = 0; index < items.Length; index++)
if (items[index] == "one")
items[index] = "zero";
简单。
为避免每次需要在代码中编写循环,请创建一个方法:
void ReplaceAll(string[] items, string oldValue, string newValue)
{
for (int index = 0; index < items.Length; index++)
if (items[index] == oldValue)
items[index] = newValue;
}
然后这样称呼它:
ReplaceAll(items, "one", "zero");
你也可以把它做成扩展方法:
static class ArrayExtensions
{
public static void ReplaceAll(this string[] items, string oldValue, string newValue)
{
for (int index = 0; index < items.Length; index++)
if (items[index] == oldValue)
items[index] = newValue;
}
}
那么你可以这样称呼它:
items.ReplaceAll("one", "zero");
当您使用它时,您可能希望使其通用:
static class ArrayExtensions
{
public static void ReplaceAll<T>(this T[] items, T oldValue, T newValue)
{
for (int index = 0; index < items.Length; index++)
if (items[index].Equals(oldValue))
items[index] = newValue;
}
}
调用站点看起来一样。
现在,这些方法都不支持自定义字符串相等检查。例如,您可能希望比较是否区分大小写。添加一个采用IEqualityComparer<T> 的重载,这样您就可以提供您喜欢的比较;这更加灵活,无论T 是string 还是其他:
static class ArrayExtensions
{
public static void ReplaceAll<T>(this T[] items, T oldValue, T newValue)
{
items.ReplaceAll(oldValue, newValue, EqualityComparer<T>.Default);
}
public static void ReplaceAll<T>(this T[] items, T oldValue, T newValue, IEqualityComparer<T> comparer)
{
for (int index = 0; index < items.Length; index++)
if (comparer.Equals(items[index], oldValue))
items[index] = newValue;
}
}