Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading