Last active
March 8, 2020 05:41
-
-
Save eral/1603163504e93a9488d299b7cbf657c4 to your computer and use it in GitHub Desktop.
OreOreLinq.Lottery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://wandbox.org/permlink/w7xxwEoqXSQVwCXC