irc-netcore-api/IRaCIS.Core.Infrastructure/Extention/RandomExtensions.cs

38 lines
1.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Infrastructure.Extention
{
public static class RandomExtensions
{
private static Random _random = new Random();
public static List<T> GetRandomCountList<T>(this List<T> list, int count)
{
if (count > list.Count)
{
throw new ArgumentException("Sample size cannot be greater than list size.");
}
// 使用 Fisher-Yates 洗牌算法来随机选择元素
List<T> result = list.ToList(); // 复制原始列表,以避免修改原始列表
int n = result.Count;
while (n > 1)
{
n--;
int k = _random.Next(n + 1);
T value = result[k];
result[k] = result[n];
result[n] = value;
}
// 返回所需数量的元素
return result.Take(count).ToList();
}
}
}