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
}
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.
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.
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.
var foo = new int[] { 1,2,3,4,5 };
foo = foo.Select(x=>x/2).ToArray();
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With