Innovenergy_trunk/csharp/lib/SysTools/Utils/EnumerableUtils.cs

103 lines
2.6 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
namespace InnovEnergy.SysTools.Utils;
internal static class EnumerableUtils
{
public static IEnumerable<T> Pad<T>(this IEnumerable<T> src, Int32 length, T padding)
{
using (var enumerator = src.GetEnumerator())
{
while (enumerator.MoveNext() && length-- > 0)
yield return enumerator.Current;
while (length-- > 0)
yield return padding;
}
}
public static Dictionary<T, IReadOnlyList<T>> IndexColumn<T>(this IEnumerable<IEnumerable<T>> src, UInt16 index)
{
var d = new Dictionary<T, IReadOnlyList<T>>();
foreach (var outer in src)
{
var inner = outer.ToList();
var key = inner[index];
d.Add(key, inner);
}
return d;
}
public static IEnumerable<(TLeft left, TRight right)> Zip<TLeft, TRight>(IEnumerable<TLeft> left,
IEnumerable<TRight> right)
{
using (var l = left.GetEnumerator())
using (var r = right.GetEnumerator())
while (l.MoveNext() && r.MoveNext())
yield return (l.Current, r.Current);
}
public static IEnumerator<T> Enumerator<T>(this T t)
{
yield return t;
}
public static IEnumerable<T> Enumerable<T>(this T t)
{
yield return t;
}
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> src) => src.SelectMany(s => s);
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (var e in enumerable)
action(e);
}
public static IEnumerable<T> Do<T>(this IEnumerable<T> enumerable, Action<T> action)
{
return enumerable.Select(e =>
{
action(e);
return e;
});
}
public static void ForEach<T,R>(this IEnumerable<T> enumerable, Func<T,R> func)
{
foreach (var e in enumerable)
func(e);
}
public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> enumerable, Func<T,Boolean> predicate)
{
return enumerable.Where(e => !predicate(e));
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> enumerable)
{
return enumerable ?? new T[0];
}
// // https://stackoverflow.com/a/34006336/141397
// public static Int32 CombineHashes(this ITuple tupled, Int32 seed = 1009, Int32 factor = 9176)
// {
// var hash = seed;
//
// for (var i = 0; i < tupled.Length; i++)
// {
// unchecked
// {
// hash = hash * factor + tupled[i].GetHashCode();
// }
// }
//
// return hash;
// }
}