Here is an alternative LINQ implementation that avoids creating anonymous objects and returns -1 if the item is not in the list:
int index = linked.Select((n, i) => n == 64 ? (int?)i : null). FirstOrDefault(n => n != null) ?? -1;
It converts a sequence of numbers into a sequence containing a match index, or null otherwise. It takes the first one, if any, otherwise converts the default value to int? at -1 .
Edit:
Here is a better (simpler and more efficient) alternative:
int i = linked.TakeWhile(n => n != 64).Count();
i will either be equal to the index, or equal to linked.Count , if the value 64 not found.
source share