0

I have a parameter userSearch.Expand where the Expand property is a string[]. I want to convert all values in this string[] to upper case. I was hoping to do something like

userSearch.Expand.ForEach(x => x = x.ToUpper());

But it looks like .ForEach() is not available on a string[].

Is there a workaround for this or a simplified way to do this or will I need to revert a more basic loop for this?

Markiian Benovskyi
  • 2,137
  • 22
  • 29
user9393635
  • 1,369
  • 4
  • 13
  • 32
  • 3
    `x = x.ToUpper()` does nothing to the element of array, regardless of whether `ForEach` is available on `string[]` or not. – Igor Mar 27 '18 at 15:57
  • 1
    https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet –  Mar 27 '18 at 15:57
  • 1
    Possible duplicate of [LINQ equivalent of foreach for IEnumerable](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) – Robert Columbia Mar 27 '18 at 16:00
  • 2
    There's nothing wrong with the 'more basic loop' as such here – d219 Mar 27 '18 at 16:08

4 Answers4

3

You can use Select instead (assuming you want to convert an array to uppercase and use it):

var lowercaseArray = new[] { "one", "two", "three" };
var uppercaseArray = lowercaseArray.Select(x => x.ToUpper()).ToArray();
ThePerplexedOne
  • 2,920
  • 15
  • 30
1

You should reassign your values or create a new variable:

var userSearchUpper = userSearch.Select(s => s.ToUpperInvariant()).ToArray();

Then you receive a new array of string in upper invariant culture.

Markiian Benovskyi
  • 2,137
  • 22
  • 29
0

You can use LINQ to create a new array to replace the existing one.

userSearch.Expand = userSearch.Expand.Select(x => x.ToUpper()).ToArray();
NetMage
  • 26,163
  • 3
  • 34
  • 55
0

No, foreach is using only for List<T>. You can read more about ForEach().

But you can use:

1) custom ForEach:

    public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
    {
        foreach (var item in collection)
            action(item);
    }

2) or, if you want replace values in this container:

    userSearch = userSearch.Select(s => s.ToUpper()).ToArray();
EgoPingvina
  • 734
  • 1
  • 10
  • 33
  • 2
    How would the custom ForEach help? strings are immutable, so calling ToUpper() in a foreach wont give the OP what they want – maccettura Mar 27 '18 at 16:11
  • it is only simple for use ForEach on arrays, if will help him in understanding – EgoPingvina Mar 27 '18 at 16:13
  • It wont help the OP in understanding because a ForEach is not what the OP needs. You are only adding more confusion and perpetuating a method that does not help the OP in _any_ way – maccettura Mar 27 '18 at 16:14