I have a List with numbers, I'd like to find the position of the minimum (not value) using LINQ
eg: {3,1,0,5} output = 2
I have a List with numbers, I'd like to find the position of the minimum (not value) using LINQ
eg: {3,1,0,5} output = 2
var list = new List<int> { 3, 1, 0, 5 };
int pos = list.IndexOf(list.Min()); // returns 2
List<int> data = new List<int>();
data.AddRange(new[] { 3, 1, 0, 5 });
Console.WriteLine(data.IndexOf(data.Min()));
var data = new List<int> { 3, 1, 0, 5 };
var result = Enumerable.Range(0, data.Count).OrderBy(n => data[n]).First();
List<int>.Enumerator e = l.GetEnumerator();
int p = 0, min = int.MaxValue, pos = -1;
while (e.MoveNext())
{
if (e.Current < min)
{
min = e.Current;
pos = p;
}
++p;
}
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...
int min = 0;
bool minIsSet = false;
var result = ints
.Select( (x, i) => new {x, i}
.OrderBy(z => z.x)
.Select(z =>
{
if (!minIsSet)
{
min = z.x;
minIsSet = true;
}
return z;
}
.TakeWhile(z => z.x == min)
.Select(z => z.i);
I don't necessarily recommend this CPS-style code, but it works and is O(n), unlike the solutions that use OrderBy:
var minIndex = list.Aggregate(
new { i = 0, mini = -1, minv = int.MaxValue },
(min, x) => (min.minv > x)
? new { i = min.i + 1, mini = min.i, minv = x }
: new { i = min.i + 1, mini = min.mini, minv = min.minv })
.mini;
Change > to >= if you want the last minimum duplicate, not the first.
Use .minv to get the minimum value or neither to get a 2-tuple with both the index and the minimum value.
I can't wait for .NET to get tuples in 4.0.