使用 LINQ 在 c# 中获取 List<> 元素位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1110789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:29:01  来源:igfitidea点击:

Get List<> element position in c# using LINQ

c#linq

提问by

I have a List with numbers, I'd like to find the position of the minimum (not value) using LINQ

我有一个带数字的列表,我想使用 LINQ 找到最小值(不是值)的位置

eg: {3,1,0,5} output = 2

例如:{3,1,0,5} 输出 = 2

采纳答案by John Rasch

var list = new List<int> { 3, 1, 0, 5 };
int pos = list.IndexOf(list.Min()); // returns 2

回答by Fredrik M?rk

List<int> data = new List<int>();
data.AddRange(new[] { 3, 1, 0, 5 });
Console.WriteLine(data.IndexOf(data.Min()));

回答by dtb

var data = new List<int> { 3, 1, 0, 5 };

var result = Enumerable.Range(0, data.Count).OrderBy(n => data[n]).First();

回答by Razvi

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;
}

回答by Guffa

As you specifically asked for a LINQ solution, and all you got was non-LINQ solutions, here's a LINQ solution:

正如您特别要求提供 LINQ 解决方案,而您得到的只是非 LINQ 解决方案,这是一个 LINQ 解决方案:

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...

然而,这并不意味着 LINQ 是这个问题的最佳解决方案......

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;
  }
}

回答by Amy B

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);

回答by Joe Chung

I don't necessarily recommend this CPS-style code, but it works and is O(n), unlike the solutions that use OrderBy:

我不一定推荐这种 CPS 风格的代码,但它可以工作并且是 O(n),与使用 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.

使用 .minv 获取最小值,或者两者都不使用以获取具有索引和最小值的二元组。

I can't wait for .NET to get tuples in 4.0.

我等不及 .NET 在 4.0 中获得元组了。

回答by shoelzer

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.

我同意 LINQ 不是这个问题的最佳解决方案,但这是 O(n) 的另一个变体。它不排序,只遍历列表一次。

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

回答by daniele3004

The best way to catch the position is by FindIndexThis function is available only for List<>

捕获位置的最佳方法是通过FindIndex此函数仅适用于 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);