You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

string[]无法使用ForEach方法转大写?求替代方案或简化实现

解决string[]转换为大写的替代方案

Ah, right—regular string[] arrays don't have the ForEach() instance method that List<T> does, which can be a bit frustrating when you're used to working with lists. No worries though, there are a few clean alternatives to get this done without writing clunky code:

1. 使用LINQ(最简洁的方案)

LINQ works seamlessly with arrays, so you can use Select() to transform each element to uppercase, then convert the result back to an array with ToArray(). This is my go-to for readability:

// 注意:如果数组元素可能为null,加上?.避免空引用异常
userSearch.Expand = userSearch.Expand.Select(x => x?.ToUpper()).ToArray();

This replaces the original array with a new one where every string is uppercase. If you need to modify the existing array in-place (instead of creating a new one), skip to the next option.

2. 基础for循环(原地修改数组)

If you want to update the existing array without creating a new one, a standard for loop is straightforward and avoids any LINQ overhead:

for (int i = 0; i < userSearch.Expand.Length; i++)
{
    // 同样处理可能的null值
    userSearch.Expand[i] = userSearch.Expand[i]?.ToUpper();
}

Unlike foreach, this lets you directly assign back to the array index since you have access to the position of each element.

3. 自定义数组扩展方法(复用性强)

If you find yourself needing this kind of "ForEach" functionality for arrays often, you can create an extension method to add this behavior yourself. Just note that since string is immutable, you can't just assign to the parameter in the action—you need to work with the array index to update values:

public static class ArrayExtensions
{
    public static void ForEach<T>(this T[] array, Action<int, T> action)
    {
        if (array == null) throw new ArgumentNullException(nameof(array));
        if (action == null) throw new ArgumentNullException(nameof(action));
        
        for (int i = 0; i < array.Length; i++)
        {
            action(i, array[i]);
        }
    }
}

Then you can use it like this:

userSearch.Expand.ForEach((index, value) => 
    userSearch.Expand[index] = value?.ToUpper());

This gives you a ForEach-like syntax for arrays, tailored to modify elements in-place.


内容的提问来源于stack exchange,提问作者user9393635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:27:29