skybrud / Skybrud.Essentials

Library with common purpose functionality for working with .NET.

Home Page:https://packages.skybrud.dk/skybrud.essentials/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Introduce `RandomOrDefault` extension method

abjerner opened this issue · comments

Eg:

/// <summary>
/// Returns a random item from the specified <paramref name="collection"/>.
/// </summary>
/// <typeparam name="T">The type the items.</typeparam>
/// <param name="collection">The collection.</param>
/// <returns>A random item of type <typeparamref name="T"/> from <paramref name="collection"/> if not empty; otherwise, the default value of <typeparamref name="T"/>.</returns>
public static T RandomOrDefault<T>(this IEnumerable<T> collection) {
    return collection.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
}