raylopez99 wrote:

I would like to know if there's a quick "Linq" way to find the index

of an array having a particular value. I can do this the long way by

sequential iteration, but would like to know if there's a shortcut.

Normally, that would be .Where(condition)...

Specifically, you have an Array, say an array of Ints. You have a

maximum value, i.e. int someValue = Array.Max(); and you would like to

know which ith cell of the Array holds this value.

....but if you're looking for the index of the maximum, that would mean going

through the array twice (first to find the maximum, then its index), which

is inefficient.

Also, if you're looking for a known value in array, Array.IndexOf() beats

..Where().

How to do this without iterating the entire array (and counting the

indexes, etc, until you come across this value)?

Finding the maximum value of an arbitrary sequence (like an array)

inherently requires examining all elements. There is no way to speed it up

without more information (like knowing that the array is sorted, so you can

immediately take the last or first element).

The best you can do is only go through the array once to find both the

maximum and its index (or rather one of its indices):

int max = int.MinValue, maxIndex = 0;

for (int i = 0; i != arr.Length; ++i) {

if (arr[i] max) {

max = arr[i];

maxIndex = i;

}

}

LINQ is of no particular help in making this clearer.

Of course you an also set up a map/dictionary, and your index would be

the key, but I would like to do this for an ordinary array.

No big deal, but I'm just trying to optimize some code (I have a 300M

int array, and arguably the Linq way might be faster than traversing

sequentially the array, though perhaps I'm mistaken).

LINQ is more expressive than manually iterating, but never more efficient

(unless you bring things like Parallel LINQ into play). It all boils down to

for-loops under the covers.

--

J.