/// <summary>
/// 使用 Fisher-Yates 算法的 Durstenfeld 实现方法对列表中的元素进行随机排序
/// 此方法会就地修改输入列表,确保每个排列出现的概率均等,并返回修改后的列表,以便进行方法链式调用
/// 参考: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
/// </summary>
/// <param name="list">需要打乱顺序的列表</param>
/// <typeparam name="T">列表中元素的类型</typeparam>
/// <returns>打乱顺序后的列表</returns>
public static IList<T> Shuffle<T>(this IList<T> list) {
Random rng = new Random();
int count = list.Count;
while (count > 1) {
--count;
int index = rng.Next(count + 1);
(list[index], list[count]) = (list[count], list[index]);
}
return list;
}
过滤集合
csharp复制代码
/// <summary>
/// Filters a collection based on a predicate and returns a new list根据条件过滤集合并返回一个新的列表。
/// containing the elements that match the specified condition.包含符合指定条件的元素。
/// </summary>
/// <param name="source">The collection to filter.需要过滤的集合</param>
/// <param name="predicate">The condition that each element is tested against.用于测试每个元素的条件。</param>
/// <returns>A new list containing elements that satisfy the predicate.一个包含满足条件的元素的新列表。</returns>
public static IList<T> Filter<T>(this IList<T> source, Predicate<T> predicate) {
List<T> list = new List<T>();
foreach (T item in source) {
if (predicate(item)) {
list.Add(item);
}
}
return list;
}