Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save AlbertoMonteiro/fb20c552fa419b78ae5a to your computer and use it in GitHub Desktop.

Select an option

Save AlbertoMonteiro/fb20c552fa419b78ae5a to your computer and use it in GitHub Desktop.
Cool Linq Extensions
static class Ex
{
public static TimeSpan Sum(this IEnumerable<TimeSpan> lista)
{
return lista.Aggregate(TimeSpan.Zero, (current, item) => current.Add(item));
}
public static TValue Aggregate<T, TValue>(this IEnumerable<T> lista, TValue initial, Func<T, int, TValue, TValue> aggregateFunc)
{
var i = 0;
return lista.Aggregate(initial, (current, item) => aggregateFunc(item, i++, current));
}
public static IEnumerable<IEnumerable<T>> LazyPartition<T>(this IEnumerable<T> lista, int quantity)
{
var total = 0 - quantity;
Func<IEnumerable<T>> a = () => lista.Skip(total += quantity).Take(quantity);
IEnumerable<T> enumerable;
while ((enumerable = a()).Any())
{
yield return enumerable;
}
}
public static IEnumerable<IList<T>> EagerPartition<T>(this IEnumerable<T> lista, int quantity)
{
var total = 0 - quantity;
Func<IList<T>> a = () => lista.Skip(total += quantity).Take(quantity).ToList();
IList<T> enumerable;
while ((enumerable = a()).Any())
yield return enumerable;
}
}
[Test]
public void Teste()
{
var oitoDaManha = new DateTime(2014, 01, 01, 8, 0, 0);
var batidas = new[]
{
oitoDaManha, //8
oitoDaManha.AddHours(4),//12
oitoDaManha.AddHours(5), //13
oitoDaManha.AddHours(9) // 17
};
var orderByDescending = batidas.OrderByDescending(p => p).ToList();
var timeSpan = orderByDescending.Aggregate(TimeSpan.Zero, (date, i, time) => i % 2 == 0 ? time.Add(date.TimeOfDay) : time.Subtract(date.TimeOfDay));
var turnos = orderByDescending.EagerPartition(2).ToList();
var tempoMaximo = turnos.Select(t => t[0].TimeOfDay - t[1].TimeOfDay).Sum();
var any = turnos.Any(t => (t[0].TimeOfDay - t[1].TimeOfDay) > TimeSpan.FromHours(6));
Assert.AreEqual(TimeSpan.FromHours(8), timeSpan);
Assert.AreEqual(TimeSpan.FromHours(8), tempoMaximo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment