forked from RPCS3/discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnumerableExtensions.cs
57 lines (46 loc) · 1.53 KB
/
EnumerableExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Linq;
namespace CompatBot.Utils;
public static class EnumerableExtensions
{
public static IEnumerable<TResult> Pairwise<T, TResult>(this IEnumerable<T> source, Func<T, T, TResult> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
using var e = source.GetEnumerator();
if (!e.MoveNext())
yield break;
T prev = e.Current;
if (!e.MoveNext())
yield break;
do
{
yield return selector(prev, e.Current);
prev = e.Current;
} while (e.MoveNext());
}
public static IEnumerable<T> Single<T>(T item)
{
yield return item;
}
public static T? RandomElement<T>(this IList<T> collection, int? seed = null)
{
if (collection.Count > 0)
{
var rng = seed.HasValue ? new(seed.Value) : new Random();
return collection[rng.Next(collection.Count)];
}
return default;
}
public static bool AnyPatchesApplied(this Dictionary<string, int> patches)
=> patches.Values.Any(v => v > 0);
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / maxItems)
.Select(g => g.Select(x => x.item));
}
}