Pair off!
Linq extension method which pairs off elements of an IEnumerable<T>. If there's an odd element left over, it's ignored.
public static IEnumerable<KeyValuePair<T, T>> PairOff<T>(this IEnumerable<T> ie)
{
IEnumerator<T> e = ie.GetEnumerator();
while (e.MoveNext())
{
T first = e.Current;
if (e.MoveNext())
yield return new KeyValuePair<T, T>(first, e.Current);
}
}
GroupBy for Mono
The Mono implementation of the GroupBy Linq extension is very slow, especially when compared to the .NET version. Here is a
replacement extension method you can use as a workaround.
public class MyGrouping<TSrc,TKey> : List<TSrc>
{
public TKey Key;
public MyGrouping(TKey k) { Key = k; }
}
public static IEnumerable<MyGrouping<TSrc, TKey>> MyGroupBy<TSrc, TKey>(this IEnumerable<TSrc> ie, Converter<TSrc,TKey> fn)
{
Dictionary<TKey, MyGrouping<TSrc, TKey>> d = new Dictionary<TKey, MyGrouping<TSrc, TKey>>();
foreach (TSrc src in ie)
{
TKey k = fn(src);
MyGrouping<TSrc,TKey> l;
if (d.TryGetValue(k, out l))
l.Add(src);
else
d.Add(k, new MyGrouping<TSrc,TKey>(k) { src });
}
return d.Values;
}
Value compare for arrays
public static bool ValueCompare(this T[] a, T[] b) where T : struct
{
if (a.Length != b.Length)
return false;
EqualityComparer q = EqualityComparer.Default;
for (int i = 0; i < a.Length; i++)
if (!q.Equals(a[i], b[i]))
return false;
return true;
}
public static bool ValueCompare(this T[] a, int a_offset, T[] b) where T : struct
{
if (a_offset >= a.Length || a_offset + b.Length > a.Length)
return false;
EqualityComparer q = EqualityComparer.Default;
for (int i = 0; i < b.Length; i++, a_offset++)
if (!q.Equals(a[a_offset], b[i]))
return false;
return true;
}
Filter for non-null references (and non-default values)
public static IEnumerable NotDefault(this IEnumerable source)
{
return source.Where(e => !Object.Equals(e,default(T)));
}
public static IEnumerable NotDefault(this IEnumerable source, Converter selector)
{
return source.Where(e => !Object.Equals(selector(e),default(TAny)));
}
DateTime to UNIX epoch
public static int ToEpoch(this DateTime dt)
{
return (int)(dt - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
}