Linq的方法
int[] array = new int[] { 1, 3, 2, 3 }; int[] result = array.Select((x, i) => new { index = i, value = x }) .GroupBy(x => x.value) .OrderByDescending(x => x.Key) .First() .Select(x => x.index) .ToArray();
首先获得最大值:
int max = array.Max();
现在获取具有该值的元素的索引:
var indices = array.Select((x, i) => new { Index = i, Value = x }) .Where(x => x.Value == max) .Select(x => x.Index);
运用 yield return 并循环遍历数组,你可以这样做:
yield return
using Linq; using System.Collections.Generic; public static class IEnumerableExtensions { // Extension method for IEnumerable public static IEnumerable<int> AllIndexesOf<T>(this IEnumerable<T> list, T searchValue) { for (int i = 0; i < list.Count(); i++) { if (list.ElementAt(i) == searchValue) { yield return i; } } } }
然后使用LINQ找到数组中的最大值并调用方法:
using Linq; // include this at the top of your file, if not already present. // ... int[] array = new int[] {1, 3, 2, 3}; IEnumerable<int> matchingIndexes = array.AllIndexesOf(array.Max()); // Convert to array if you need one int[] matchingIndexesArr = matchingIndexes.ToArray();
您可以找到有关扩展方法的更多信息 在文档中 。