Get List<> element position in c# using LINQ
var list = new List<int> { 3, 1, 0, 5 };
int pos = list.IndexOf(list.Min()); // returns 2
As you specifically asked for a LINQ solution, and all you got was non-LINQ solutions, here's a LINQ solution:
List<int> values = new List<int> { 3, 1, 0, 5 };
int index =
values
.Select((n, i) => new { Value = n, Index = i })
.OrderBy(n=>n.Value)
.First()
.Index;
That however doesn't mean that LINQ is the best solution for this problem...
Edit:
With a bit more complex code this performs a little better:
int index =
values
.Select((n, i) => new { Value = n, Index = i })
.Aggregate((a,b) => a.Value < b.Value ? a : b)
.Index;
To get the best performance, you would use a plain loop go get through the items, while you keep track of the lowest:
int index = 0, value = values[0];
for (int i = 1; i < values.Length; i++) {
if (values[i] < value) {
value = values[i];
index = i;
}
}
The best way to catch the position is by FindIndex
This function is available only for List<>
Example
int id = listMyObject.FindIndex(x => x.Id == 15);
If you have enumerator or array use this way
int id = myEnumerator.ToList().FindIndex(x => x.Id == 15);
or
int id = myArray.ToList().FindIndex(x => x.Id == 15);