C#如果存在重复值(查找最高数组值和索引),如何查找其他索引?
我看到这篇文章: 我还有一个问题:如果存在重复值,如何找到其他索引 假设数组是C#如果存在重复值(查找最高数组值和索引),如何查找其他索引?,c#,arrays,C#,Arrays,我看到这篇文章: 我还有一个问题:如果存在重复值,如何找到其他索引 假设数组是 int[] anArray = { 1, 5, 2, 7 , 7 , 3}; int maxValue = anArray.Max(); int maxIndex = anArray.ToList().IndexOf(maxValue); 如果使用本文中的方法,如何找到其他索引 您的问题是“如何找到其他索引”,但应该是“如何找到所有其他索引”,因为可能有多个索引 int[] anArray = { 1, 5, 2
int[] anArray = { 1, 5, 2, 7 , 7 , 3};
int maxValue = anArray.Max();
int maxIndex = anArray.ToList().IndexOf(maxValue);
如果使用本文中的方法,如何找到其他索引 您的问题是“如何找到其他索引”,但应该是“如何找到所有其他索引”,因为可能有多个索引
int[] anArray = { 1, 5, 2, 7, 7, 3 };
int maxValue = anArray.Max();
int maxIndexes =
anArray
.Select((x, i) => new { x, i }) //add indexes to sequence
.Where(x => x == maxValue) //filter on maxValue
.Select(x => x.i) //only select index
.ToList(); //ToList is optional
如果您只需要最后一个索引,或者您确定最多有一个这样的索引,只需使用.last()
或类似的方法结束查询。您的问题是“如何查找其他索引”,但应该是“如何查找所有其他索引”,因为可能有多个索引
int[] anArray = { 1, 5, 2, 7, 7, 3 };
int maxValue = anArray.Max();
int maxIndexes =
anArray
.Select((x, i) => new { x, i }) //add indexes to sequence
.Where(x => x == maxValue) //filter on maxValue
.Select(x => x.i) //only select index
.ToList(); //ToList is optional
如果您只需要最后一个索引,或者您确定最多有一个这样的索引,只需使用
.last()
或类似的方法结束查询。这将回答您的问题。Use LastIndexOf()将查找指定值的最后一个索引;)
这样,您将获得此值的最后一个索引和最后一个索引:
int maxValue = anArray.Max()
int index = anArray.ToList().LastIndexOf(maxValue);
这回答了你的问题。Use LastIndexOf()将查找指定值的最后一个索引;) 这样,您将获得此值的最后一个索引和最后一个索引:
int maxValue = anArray.Max()
int index = anArray.ToList().LastIndexOf(maxValue);
请参阅已接受的答案 所有LINQ方法都经过精心设计,只对源序列迭代一次(当它们迭代一次时)。因此,我们使用从LINQ到循环的
Enumerable.Range
表达式
int[] anArray = { 1, 5, 2, 7 , 7 , 3};
int maxValue = anArray.Max();
var result = Enumerable.Range(0, anArray.Count())
.Where(i => anArray[i] == maxValue)
.ToList();
额外信息:
Enumerable.Range
自动排除最高索引,anArray.Count()
所有LINQ方法都经过精心设计,只对源序列迭代一次(当它们迭代一次时)。因此,我们使用从LINQ到循环的Enumerable.Range
表达式
int[] anArray = { 1, 5, 2, 7 , 7 , 3};
int maxValue = anArray.Max();
var result = Enumerable.Range(0, anArray.Count())
.Where(i => anArray[i] == maxValue)
.ToList();
额外信息:Enumerable.Range
自动排除最高索引,anArray.Count()