Search code examples
c#linq

using linq to select and change values over/under a certain threshold C#


As the title suggest, is there anyway of assigning all values in an array over 250 to 250 and all values under 0 to 0? I've tried using a simple if statement but since I have a foreach loop I can't assign the iteration variable.

int[] rgbArray = { 10, 260, -10};
 foreach (int i in rgbArray)
    {
        if (i < 0)
        {
            //do something
        }
        else if (i > 250)
        {
            //do something
        }

Solution

  • A for loop will do the job, just use the iterator as the array index.

    Example:

    int[] rgbArray = { 10, 260, -10 };
    for (var i = 0; i < rgbArray.Length; i++)
    {
        if (rgbArray[i] < 0)
        {
            rgbArray[i] = 0;
        }
        else if (i > 250)
        {
            rgbArray[i] = 250;
        }
    }
    

    If it was to be done with LINQ it'd be something like this, where I'd argue the former example is much easier to read.

    rgbArray = rgbArray.Select(x => x < 0 ? 0 : x > 250 ? 250 : x).ToArray();