I have a linked list constructed as follows:
LinkedList linked = new LinkedList();
var array = new int[] { 23, 55, 64, 65 };
foreach (
Here is an alternate 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 the sequence of numbers to a sequence containing the index of a match or null otherwise. It takes the first of these if there is one, otherwise converts the default int? to -1.
Edit:
Here is a better (simpler and more performant) 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 was not found.