wabbajack/Wabbajack.Common/IEnumerableExtensions.cs

53 lines
1.3 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
2021-10-21 03:18:15 +00:00
using System.Threading.Tasks;
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Common;
public static class IEnumerableExtensions
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
public static void Do<T>(this IEnumerable<T> coll, Action<T> f)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
foreach (var i in coll) f(i);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public static IEnumerable<TOut> TryKeep<TIn, TOut>(this IEnumerable<TIn> coll, Func<TIn, (bool, TOut)> fn)
{
return coll.Select(fn).Where(p => p.Item1).Select(p => p.Item2);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> coll)
{
var rnd = new Random();
var data = coll.ToArray();
for (var x = 0; x < data.Length; x++)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
var a = rnd.Next(0, data.Length);
var b = rnd.Next(0, data.Length);
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
(data[b], data[a]) = (data[a], data[b]);
2021-09-27 12:42:46 +00:00
}
2021-10-23 16:51:17 +00:00
return data;
}
public static IEnumerable<T> OnEach<T>(this IEnumerable<T> coll, Action<T> fn)
{
foreach (var itm in coll)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
fn(itm);
yield return itm;
2021-09-27 12:42:46 +00:00
}
2021-10-23 16:51:17 +00:00
}
public static async IAsyncEnumerable<T> OnEach<T>(this IEnumerable<T> coll, Func<T, Task> fn)
{
foreach (var itm in coll)
2021-10-21 03:18:15 +00:00
{
2021-10-23 16:51:17 +00:00
await fn(itm);
yield return itm;
2021-10-21 03:18:15 +00:00
}
2021-09-27 12:42:46 +00:00
}
}