I’m having hard time with switching to LINQ with the following example:
int[] inputs = { 5, 3, 5, 66, 4, 5 };
int[] indexes; // I want to have the indexes of '5's in
// the inputs array, which is { 0, 2, 5 }
// My way (traditional for loop)
List<int> indexesList = new List<int>();
for (int i = 0; i < inputs.Length; i++)
if (inputs[i] == 5)
indexesList.Add(i);
indexes = indexesList.ToArray();
// LINQ way
var indexes = inputs.Select((s, i) => new { i, s })
.Where(t => t.s == 5)
.Select(t => t.i).ToArray();
Question 1. In terms of efficiency (speed, memory usage), am I going to have any advantage if I convert my code to LINQ?
Question 2. If true, is there a more elegant way of doing it with LINQ?
PS: Note that, this method is called very frequently in my real project. So, having a little improvement in speed or memory usage will help the overall process a lot.
You are certainly not going to have a performance advantage if your use the LINQ code. This is evident simply by reading it: to associate each value with its index, a new object is created:
These anonymous objects serve no other purpose than being a vessel to glue index together with value; therefore all the associated memory management is pure overhead compared to straight up keeping a counter.
One might say that LINQ provides a readability advantage because most of the time it highlights the intent instead of the mechanism, but in this particular case I don’t think it’s any better than the prosaic solution.