C# 提供了一种获取第一个匹配条目的索引的方法:
int first = myList.IndexOf(myList.Min())
以及获取最后一个索引的方法:
int last = myList.LastIndexOf(myList.Min())
获取匹配值的随机索引的最简单方法是什么,例如:
int anyOldOne = myList.RandomIndexOf(myList.Min())
最佳答案
可以获取所有索引,并选择一个随机索引:
// Do this once only
var rnd = new Random();
// Do this each time you want a random element.
var key = myList.Min();
var indices = mylist
.Select((n,index) => new { n, index })
.Where(x => x.n == key)
.Select(x => x.index)
.ToList();
int anyOldOne= indices[rnd.Next(indices.Count)];
当然,这在某种方法中看起来会更好。
关于c# - 获取随机匹配值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26296479/