Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq is there a way to perform an operation on every element in an Array

Tags:

c#

linq

If I have an array

var foo = new int[] { 1,2,3,4,5 };

Using linq can I perform an operation on each element instead of doing something like this?

for (int i = 0; i < foo.Length; i++)
{
    foo[i] = foo[i] / 2; //divide each element by 2
}
like image 631
ojhawkins Avatar asked Aug 21 '13 05:08

ojhawkins


People also ask

Can LINQ query work with array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

How use all in LINQ C#?

The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


2 Answers

var foo = new int[] { 1,2,3,4,5 };
foo = foo.Select(x=>x/2).ToArray();
like image 114
King King Avatar answered Sep 27 '22 18:09

King King


Those are bad solutions in my opinion. Select().ToArray() creates new collection, meaning that it might cause both performance and memory issues for larger arrays. If you want a shorter syntax - write extension methods:

static class ArrayExtensions
{
    public static void ForEach<T>(this T[] array, Func<T,T> action)
    {
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = action(array[i]);
        }
    }

    public static void ForEach<T>(this T[] array, Action<T> action)
    {
        for (int i = 0; i < array.Length; i++)
        {
            action(array[i]);
        }
    }   
}

//usage
foo.ForEach(x => x/2)
foo.ForEach(x => Console.WriteLine(x));
like image 43
Nikita B Avatar answered Sep 27 '22 16:09

Nikita B