c# - 获取随机匹配值的索引

标签 c# list

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/

相关文章:

c# - Windows 应用商店应用程序 - XAML - C# - 在代码中访问 ThemeResource

c# - 从 TPL 任务向 WPF View 报告进度的适当方法是什么?

list - 如何在 F# 中使用可变列表?

python - 如何遍历列表,获取每对可能的值?

python - Pandas 重采样的问题

python - 如何 for 循环遍历两个嵌套循环内的字符串列表并避免外部循环造成的冗余?

c# - 使用 GetType() 创建 List<T>

c# - ASP.NET MVC 3 不显示适当的 View ,使用 jquery 调用的操作

c# - 如何开启反序列化json的类类型?

c# - 如何下载 HTTPS 网页的内容?