Get List<> element position in c# using LINQ
C#.NetLinq.Net CorePositionC# Problem Overview
I have a List
Example:
var lst = new List<int>() { 3, 1, 0, 5 };
Now I am looking for a function returning me >output = 2
because the minimum is at position 2 in the list.
C# Solutions
Solution 1 - C#
var list = new List<int> { 3, 1, 0, 5 };
int pos = list.IndexOf(list.Min()); // returns 2
Solution 2 - C#
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;
}
}
Solution 3 - C#
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);
Solution 4 - C#
I agree that LINQ isn't the best solution for this problem, but here's another variation that is O(n). It doesn't sort and only traverses the list once.
var list = new List<int> { 3, 1, 0, 5 };
int pos = Enumerable.Range(0, list.Count)
.Aggregate((a, b) => (list[a] < list[b]) ? a : b); // returns 2
Solution 5 - C#
var data = new List<int> { 3, 1, 0, 5 };
var result = Enumerable.Range(0, data.Count).OrderBy(n => data[n]).First();
Solution 6 - C#
A list can contain multiple elements which are equal to the minimum value (see below).
The generic extension method .FindEveryIndex()
I wrote works with integers, strings, ... and is quite flexible because you can specify your condition as Lambda expression.
Another advantage is that it returns a list of all indices matching the condition, not just the first element.
Regarding your question: The minimum can be returned as:
var lst = new List<int>() { 1, 2, 1, 3, 4, 1 }; // example list
var minimum = lst.Min(); // get the minumum value of lst
var idx = lst.FindEveryIndex(x => x == minimum); // finds all indices matching condition
Console.WriteLine($"Output: {String.Join(',', idx.ToArray())}"); // show list of indices
It will return the indices 0, 2 and 5, because the minimum in lst1
is 1
:
> Output: 0,2,5
Example 2:
void Main()
{
// working with list of integers
var lst1 = new List<int>() { 1, 2, 1, 3, 4, 1 };
lst1.FindEveryIndex(x => x==1).Dump("Find 1"); // finds indices: [0, 2, 5]
lst1.FindEveryIndex(x => x==2).Dump("Find 2"); // finds index: [1]
lst1.FindEveryIndex(x => x==9).Dump("Find 9"); // returns [-1]
// working with list of strings
var lst2 = new List<string>() { "A", "B", "A", "C", "D", "A"};
lst2.FindEveryIndex(x => x=="A").Dump("Find A"); // finds indices: [0, 2, 5]
lst2.FindEveryIndex(x => x=="B").Dump("Find B"); // finds index: [1]
lst2.FindEveryIndex(x => x=="X").Dump("Find X"); // returns [-1]
}
Extension class:
public static class Extension
{
// using System.Collections.Generic;
public static IEnumerable<int> FindEveryIndex<T>(this IEnumerable<T> items,
Predicate<T> predicate)
{
int index = 0; bool found = false;
foreach (var item in items)
{
if (predicate(item))
{
found = true; yield return index;
};
index++;
}
if (!found) yield return -1;
}
}
Note: Copy the two code snippets into a LinqPad C# program and it works instantly.
Or, run it online with DotNetFiddle.
Solution 7 - C#
List<int> data = new List<int>();
data.AddRange(new[] { 3, 1, 0, 5 });
Console.WriteLine(data.IndexOf(data.Min()));
Solution 8 - C#
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);
Solution 9 - C#
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.
Solution 10 - C#
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;
}