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

50 c# linq

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

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

Joh*_*sch 73

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

  • @mgroves - 它返回最小的第一个索引 (3认同)
  • (IndexOf)搜索指定的对象,并返回整个List <(Of <(T>)>)中第一次出现的从零开始的索引.http://msdn.microsoft.com/en-us/library/e4w08k17.aspx (3认同)
  • 如果列表中的另一个项目也是0,会发生什么?我不批评,我只是想知道. (2认同)
  • 我认为IndexOf返回指定参数的第一个索引,如果找不到则返回-1. (2认同)

Guf*_*ffa 40

当您特别要求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;
Run Code Online (Sandbox Code Playgroud)

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

编辑:

使用更复杂的代码,这会更好一些:

int index =
   values
   .Select((n, i) => new { Value = n, Index = i })
   .Aggregate((a,b) => a.Value < b.Value ? a : b)
   .Index;
Run Code Online (Sandbox Code Playgroud)

为了获得最佳性能,您将使用一个简单的循环来获取项目,同时跟踪最低的:

int index = 0, value = values[0];
for (int i = 1; i < values.Length; i++) {
  if (values[i] < value) {
    value = values[i];
    index = i;
  }
}
Run Code Online (Sandbox Code Playgroud)


dan*_*004 9

捕获位置的最佳方法是FindIndex 此功能仅适用于List <>

int id = listMyObject.FindIndex(x => x.Id == 15); 
Run Code Online (Sandbox Code Playgroud)

如果你有枚举器或数组使用这种方式

int id = myEnumerator.ToList().FindIndex(x => x.Id == 15); 
Run Code Online (Sandbox Code Playgroud)

要么

   int id = myArray.ToList().FindIndex(x => x.Id == 15); 
Run Code Online (Sandbox Code Playgroud)