C# List 随机选取元素 - 使用 LINQ 和 Random
在 C# 中,可以使用 Random 类的 Next 方法生成随机数,然后使用 LINQ 的 Take 方法从 List 中挑选指定数量的元素。下面是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person('Alice', 20));
people.Add(new Person('Bob', 25));
people.Add(new Person('Charlie', 30));
people.Add(new Person('Dave', 35));
people.Add(new Person('Eve', 40));
List<Person> randomPeople = people.OrderBy(p => Guid.NewGuid()).Take(5).ToList();
Console.WriteLine('Randomly selected 5 people:');
foreach (Person person in randomPeople)
{
Console.WriteLine(person.Name);
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
运行结果可能类似于:
Randomly selected 5 people:
Eve
Dave
Charlie
Bob
Alice
原文地址: https://www.cveoy.top/t/topic/oYoL 著作权归作者所有。请勿转载和采集!