Skip to content

Instantly share code, notes, and snippets.

@eral
Last active March 8, 2020 05:41
Show Gist options
  • Save eral/1603163504e93a9488d299b7cbf657c4 to your computer and use it in GitHub Desktop.
Save eral/1603163504e93a9488d299b7cbf657c4 to your computer and use it in GitHub Desktop.
OreOreLinq.Lottery
// Created by ERAL
// These codes are licensed under CC0.
// https://creativecommons.org/publicdomain/zero/1.0/
namespace OreOreLinq
{
using System;
using System.Collections.Generic;
public static class Enumerable
{
public static TSource Lottery<TSource>(this IEnumerable<TSource> source, Func<TSource,bool> predicate) {
var result = default(TSource);
var random = new Random();
var index = 0;
foreach (var s in source) {
if (predicate(s)) {
++index;
if (random.Next(index) == 0) {
result = s;
}
}
}
if (index == 0) {
throw new InvalidOperationException();
}
return result;
}
}
}
@eral
Copy link
Author

eral commented Mar 8, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment