-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListExtensions.cs
75 lines (65 loc) · 1.88 KB
/
ListExtensions.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#nullable enable
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace System.Collections.Generic
{
public static class ListExtensions
{
public static T Pop<T>(this IList<T> source)
{
T obj = source[0];
source.RemoveAt(0);
return obj;
}
public static bool TryPop<T>(this IList<T> source, [NotNullWhen(true)] out T? obj)
{
if (source.Count == 0)
{
obj = default;
return false;
}
obj = source.Pop()!;
return true;
}
public static T RandomElement<T>(this IList<T> source) => RandomExtensions.Instance.Choose(source);
public static void AddRange<T>(this IList<T> source, IEnumerable<T> items) => items.ForEach(source.Add);
public static void AddRange<T>(this IList<T> source, int count, Func<T> factory) => Enumerable.Range(0, count).Select(_ => factory()).ForEach(source.Add);
public static void Move<T>(this IList<T> source, T item, int index)
{
source.Remove(item);
source.Insert(index, item);
}
public static void Shuffle<T>(this IList<T?> source)
{
for (int n = 0; n < source.Count; n++)
source.Swap(n, RandomExtensions.Instance.Next(source.Count));
}
public static void Swap<T>(this IList<T?> source, int i1, int i2)
{
if (i1 == i2) return;
int maxIndex = Math.Max(i1, i2);
int minIndex = Math.Min(i1, i2);
source.RemoveAt(maxIndex, out T? maxItem);
source.RemoveAt(minIndex, out T? minItem);
source.Insert(minIndex, maxItem);
source.Insert(maxIndex, minItem);
}
public static bool RemoveAt<T>(this IList<T?> source, int index, out T? item)
{
if (index < 0 || index >= source.Count)
{
item = default;
return false;
}
item = source[index];
source.RemoveAt(index);
return true;
}
public static bool AddIfDistinct<T>(this IList<T> source, T item)
{
if (source.Contains(item)) return false;
source.Add(item);
return true;
}
}
}