As you may have noticed, ILNumerics arrays implement the IEnumerable interface. This makes them compatible with ‘foreach’ loops and all the nice features of LINQ!
Consider the following example: (Dont forget to include ‘using System.Linq’ and derive your class from ILNumerics.ILMath!)
ILArray<double> A = vec(0, 10); Console.WriteLine(String.Join(Environment.NewLine, A)); Console.WriteLine("Evens from A:"); var evens = from a in A where a % 2 == 0 select a; Console.WriteLine(String.Join(Environment.NewLine, evens)); Console.ReadKey(); return;
Some people like the Extensions syntax more:
var evens = A.Where(a => a % 2 == 0);
I personally find both equivalently expressive.
Considerations for IEnumerable<T> on ILArray<T>
No option exist in IEnumerable<T> to specify a dimensionality. Therefore, and since ILNumerics arrays store their elements in column major order, enumerating an ILNumerics array will be done along the first dimension. Therefore, when used on a matrix, the enumerator runs along the columns:
ILArray<double> A = counter(3,4); Console.WriteLine(A + Environment.NewLine); Console.WriteLine("IEnumerable:"); foreach(var a in A) Console.WriteLine(a);
… will give the following:
<Double> [3,4] 1 4 7 10 2 5 8 11 3 6 9 12 IEnumerable: 1 2 3 4 5 6 7 8 9 10 11 12
Secondly, as is well known, accessing elements returned from IEnumerable<T> is only possible in a read-only manner! In order to alter elements of ILNumerics arrays, one should use the explicit API provided by our arrays. See SetValue, SetRange, A[..] = .. and GetArrayForWrite()
Lastly, performance considerations arise by excessive utilization of IEnumerable<T> in such situations, where high performance computations are desirable. ILNumerics does integrate well with IEnumerable<T> – but how well IEnumerable<T> does integrate into the memory management of ILNumerics should be investigated with help of your favorite profiler. I would suspect, most every day scenarios do work out pretty good with LINQ since it concatenates all expressions and queries and iterates the ILNumerics array only once. However, let us know your experiences!