获取随机匹配值的索引

本文关键字:索引 随机 获取 | 更新日期: 2023-09-27 18:26:06

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)];

当然,这在一种方法中看起来会更好。

你可以试试这个,我已经创建了一个扩展方法,可以像你在问题中问的那样直接使用:-

扩展方法:-

public static int RandomIndexOf<T>(this IList<T> sequence, T element)
        {
            Random rnd = new Random();
            List<int> matchedIndexs = new List<int>();
            for (int i = 0; i < sequence.Count; i++)
            {
                if (sequence[i].Equals(element))
                    matchedIndexs.Add(i);
            }
            return matchedIndexs[rnd.Next(matchedIndexs.Count)];
        }

然后你可以简单地使用它:-

            //Dummy Data Source
            List<int> myList = new List<int> { 4, 1, 5, 7, 1, 2, 1, 4, 1, 4, 6, 1, 1 };
            int random = myList.RandomIndexOf(myList.Min());

也许:

int min = myList.Min();
var allIndicesWithThatValue = myList
    .Select((i, index) => new { value = i, index })
    .Where(x => x.value == min);
Random rnd = new Random();
int randomIndex = allIndicesWithThatValue
    .ElementAt(rnd.Next(allIndicesWithThatValue.Count())).index;

请注意,您不应该在循环中调用此函数,因为Random是用当前时间播种的。在这种情况下,您应该重用相同的Random实例。否则,您将始终获得相同的索引。