This repository was archived by the owner on Jun 4, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinqExtensions.cs
More file actions
332 lines (286 loc) · 12 KB
/
Copy pathLinqExtensions.cs
File metadata and controls
332 lines (286 loc) · 12 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#nullable enable
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using TooManyExtensions;
namespace System.Linq
{
public static class LinqExtensions
{
public static IEnumerable<(int index, T item)> Enumerate<T>(this IEnumerable<T> source)
{
int i = 0;
foreach (T item in source)
yield return (i++, item);
}
public static bool All(this IEnumerable<bool> source) => source.All(b => b);
public static bool Any(this IEnumerable<bool> source) => source.Any(b => b);
public static TResult InvokeWith<T1, T2, TResult>(this Func<T1, T2, TResult> func, (T1, T2) args) => func(args.Item1, args.Item2);
public static void InvokeWith<T1, T2>(this Action<T1, T2> func, (T1, T2) args) => func(args.Item1, args.Item2);
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> source) => source.SelectMany(item => item);
public static IEnumerable<T> Process<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
{
action(item);
yield return item;
}
}
public static IEnumerable<T> Pivot<T>(this IEnumerable<T> source, int index)
{
IEnumerable<T> first = Enumerable.Empty<T>();
int i = 0;
foreach (T item in source)
{
if (i++ < index)
first = first.Append(item);
else
yield return item;
}
foreach (T item in first)
yield return item;
}
public static (IEnumerable<T>, IEnumerable<T>) Split<T>(this IEnumerable<T> source, int index)
{
IEnumerable<T> first = Enumerable.Empty<T>();
IEnumerable<T> last = Enumerable.Empty<T>();
int i = 0;
foreach (T item in source)
{
if (i >= index)
first = first.Append(item);
else
last = last.Append(item);
i++;
}
return (first, last);
}
public static IEnumerable<T> Insert<T>(this IEnumerable<T> enumerable, int index, T newItem)
{
int i = 0;
foreach (T item in enumerable)
{
if (i++ == index)
yield return newItem;
yield return item;
}
}
public static T? ElementAtOrLast<T>(this IEnumerable<T?> enumerable, int index)
{
T? last = default;
int i = 0;
foreach (T? item in enumerable)
{
last = item;
if (i == index)
return last;
i++;
}
return last;
}
public static IEnumerable<(TFirst, TSecond)> Zip<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second)
{
return first.Zip(second, (firstItem, secondItem) => (firstItem, secondItem));
}
public static IEnumerable<(TFirst, TSecond, TThird)> Zip<TFirst, TSecond, TThird>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third)
{
return Zip(first, second).Zip(third, (firstSecond, thirdItem) => (firstSecond.Item1, firstSecond.Item2, thirdItem));
}
public static IEnumerable<(TFirst, TSecond, TThird, TFourth)> Zip<TFirst, TSecond, TThird, TFourth>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, IEnumerable<TFourth> fourth)
{
return Zip(first, second, third).Zip(fourth, (firstSecondThird, fourthItem) => (firstSecondThird.Item1, firstSecondThird.Item2, firstSecondThird.Item3, fourthItem));
}
public static (TFirst, TSecond) Zipper<TFirst, TSecond>(TFirst first, TSecond second) => (first, second);
public static IEnumerable<(T?, T?)> ZipOrDefault<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T> generator) => ZipOrDefault(first, second, generator, generator, Zipper);
public static IEnumerable<(TFirst?, TSecond?)> ZipOrDefault<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second) => ZipOrDefault(first, second, () => default, () => default, Zipper);
public static IEnumerable<TResult?> ZipOrDefault<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst?> firstGenerator, Func<TSecond?> secondGenerator, Func<TFirst?, TSecond?, TResult> zipper)
{
using IEnumerator<TFirst?> firstEnumerator = first.GetEnumerator();
using IEnumerator<TSecond?> secondEnumerator = second.GetEnumerator();
bool hasFirst = true;
bool hasSecond = true;
while (true)
{
if (hasFirst) hasFirst = firstEnumerator.MoveNext();
if (hasSecond) hasSecond = secondEnumerator.MoveNext();
if (!hasFirst && !hasSecond)
break;
yield return zipper(hasFirst ? firstEnumerator.Current : firstGenerator(), hasSecond ? secondEnumerator.Current : secondGenerator());
}
}
public static IEnumerable<TResult> Zip<TSource, TResult>(this IEnumerable<IEnumerable<TSource>> source, Func<IEnumerable<TSource>, TResult> zipper)
{
// ReSharper disable once NotDisposedResourceIsReturned
// MustDisposeResourceAttribute isn't in Unity's copy of Jetbrains Annotations, so... ignore for now
List<IEnumerator<TSource>> enumerators = source.Select(layer => layer.GetEnumerator()).ToList();
while (true)
{
List<IEnumerator<TSource>> currentEnumerators = enumerators.Where(enumerator => enumerator.MoveNext()).ToList();
if (!currentEnumerators.Any())
{
enumerators.ForEach(enumerator => enumerator.Dispose());
yield break;
}
yield return zipper(currentEnumerators.Select(enumerator => enumerator.Current));
}
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T t in source)
action(t);
}
public static void ForEach<T1, T2>(this IEnumerable<(T1, T2)> source, Action<T1, T2> action)
{
foreach ((T1 item1, T2 item2) in source)
action(item1, item2);
}
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IList<T> source, int count)
{
for (int i = 0; i * count < source.Count; i++)
yield return source.Skip(i * count).Take(count);
}
public static bool StartsWith<T>(this IEnumerable<T> source, IEnumerable<T> prefix, IEqualityComparer<T>? comparer = null)
{
comparer ??= EqualityComparer<T>.Default;
using IEnumerator<T> sourceEnumerator = source.GetEnumerator();
using IEnumerator<T> prefixEnumerator = prefix.GetEnumerator();
while (true)
{
if (!sourceEnumerator.MoveNext())
return !prefixEnumerator.MoveNext();
if (!prefixEnumerator.MoveNext())
return true;
if (!comparer.Equals(sourceEnumerator.Current, prefixEnumerator.Current))
return false;
}
}
public static bool StartsWith<T>(this IEnumerable<T> source, T prefix, IEqualityComparer<T>? comparer = null)
{
comparer ??= EqualityComparer<T>.Default;
using IEnumerator<T> sourceEnumerator = source.GetEnumerator();
return sourceEnumerator.MoveNext() && comparer.Equals(sourceEnumerator.Current, prefix);
}
public static T? MinBy<T, TSelected>(this IEnumerable<T> source, Func<T, TSelected> selector, bool orDefault = false)
{
IComparer<TSelected> comparer = Comparer<TSelected>.Default;
return source.AggregateBy(selector, (current, item) => comparer.Compare(item, current) < 0, orDefault: orDefault);
}
public static T? MaxBy<T, TSelected>(this IEnumerable<T> source, Func<T, TSelected> selector, bool orDefault = false)
{
IComparer<TSelected> comparer = Comparer<TSelected>.Default;
return source.AggregateBy(selector, (current, item) => comparer.Compare(item, current) > 0, orDefault: orDefault);
}
public static T? AggregateBy<T, TSelected>(this IEnumerable<T> source, Func<T, TSelected> selector, Func<TSelected, TSelected, bool> comparer, bool orDefault = false)
{
bool initialized = false;
T? min = default;
TSelected? minSelected = default;
foreach (T item in source)
{
TSelected itemSelected = selector(item);
if (!initialized || comparer(minSelected!, itemSelected))
{
min = item;
minSelected = itemSelected;
}
initialized = true;
}
if (initialized || orDefault)
return min;
throw new ArgumentException("Source is empty", nameof(source));
}
public static void UpdateContentsOf<TSource, TOther>(
this IEnumerable<TSource?> source,
IEnumerable<TOther?> other,
Func<TSource, TOther?> map,
Func<TSource, TOther> add,
Action<TOther> remove,
Action<TOther, int> move)
where TSource : notnull
where TOther : notnull
{
List<TSource?> sourceList = source.ToList();
if (!sourceList.WhereNotNull().IsDistinct())
throw new InvalidOperationException("Source list contained duplicate items.");
List<TOther?> otherList = other.ToList();
if (!otherList.WhereNotNull().IsDistinct())
throw new InvalidOperationException("Other list contained duplicate items.");
Dictionary<TSource, TOther> mapDict = sourceList.WhereNotNull().Pair(map).WhereValueNotNull().ToDictionary();
sourceList.WhereNotNull().Where(sourceItem => !mapDict.ContainsKey(sourceItem)).ForEach(sourceItem =>
{
TOther otherItem = add(sourceItem);
otherList.Add(otherItem);
mapDict.Add(sourceItem, otherItem);
});
otherList.WhereNotNull().Where(otherItem => !mapDict.ContainsValue(otherItem)).ToList().ForEach(otherItem =>
{
remove(otherItem);
otherList.Remove(otherItem);
});
if (sourceList.WhereNotNull().Count() != otherList.WhereNotNull().Count())
throw new Exception($"Source and other lists were not the same length once items were added/removed.\n{sourceList.ToDelimString()} vs {otherList.ToDelimString()} with mapDict {mapDict.ToDelimString()}");
for (int sourceIndex = 0, otherIndex = 0; sourceIndex < sourceList.Count; sourceIndex++, otherIndex++)
{
if (!sourceList.NextNonNullItem(ref sourceIndex, out TSource sourceItem)) break;
if (!otherList.NextNonNullItem(ref otherIndex, out TOther actualOtherItem)) break;
TOther theoreticalOtherItem = mapDict[sourceItem];
if (!theoreticalOtherItem.Equals(actualOtherItem))
{
move(theoreticalOtherItem, otherIndex);
otherList.Move(theoreticalOtherItem, otherIndex);
}
}
}
private static bool NextNonNullItem<T>(this IEnumerable<T?> source, ref int index, out T item)
{
if (source.Skip(index).Enumerate().WhereValueNotNull().TryFirst(out (int Index, T Item) enumeration))
{
index += enumeration.Index;
item = enumeration.Item;
return true;
}
else
{
item = default!;
return false;
}
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) => source.Where(item => item is not null)!;
public static IEnumerable<(T1, T2)> WhereKeyNotNull<T1, T2>(this IEnumerable<(T1?, T2)> source) => source.Where(item => item.Item1 is not null)!;
public static IEnumerable<(T1, T2)> WhereValueNotNull<T1, T2>(this IEnumerable<(T1, T2?)> source) => source.Where(item => item.Item2 is not null)!;
#if !NET8_0_OR_GREATER
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<(TKey Key, TValue Value)> source) where TKey : notnull => source.ToDictionary(tuple => tuple.Key, tuple => tuple.Value);
#endif
public static bool TryFirst<T>(this IEnumerable<T> source, [NotNullWhen(true)] out T? item)
{
foreach (T sourceItem in source)
{
item = sourceItem!;
return true;
}
item = default;
return false;
}
public static bool TryFirst<T>(this IEnumerable<T> source, Func<T, bool> predicate, [NotNullWhen(true)] out T? item)
{
foreach (T sourceItem in source)
{
if (predicate(sourceItem))
{
item = sourceItem!;
return true;
}
}
item = default;
return false;
}
public static Result<T, TErr> First<T, TErr>(this IEnumerable<T> source, Func<T, bool> predicate, TErr err) => source.TryFirst(predicate, out T? result) ? Result.Ok<T, TErr>(result) : Result.Err<T, TErr>(err);
public static bool IsDistinct<T>(this IEnumerable<T> source)
{
IList<T> sourceList = source.ToAsList();
return sourceList.Distinct().Count() == sourceList.Count;
}
public static IList<T> ToAsList<T>(this IEnumerable<T> source) => source as IList<T> ?? source.ToList();
public static IEnumerable<(T1, T2)> Pair<T1, T2>(this IEnumerable<T1> source, Func<T1, T2> map) => source.Select(item => (item, map(item)));
public static IEnumerable<(T1, T2)> PairKey<T1, T2>(this IEnumerable<T2> source, Func<T2, T1> map) => source.Select(item => (map(item), item));
}
}