Last active
November 11, 2019 23:32
-
-
Save TheFo2sh/ce431f293d545f2a2fccdee55a467908 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class LinQToTaskExtensions | |
{ | |
public static Func<Task<TResult>> Select<TSource, TResult>( | |
this Task<TSource> source, Func<TSource, TResult> selector) | |
{ | |
return async () => | |
{ | |
var sourceResult = await source; | |
if (sourceResult == null) | |
return default(TResult); | |
return selector(sourceResult); | |
}; | |
} | |
public static Func<Task<TResult>> SelectMany<TSource, TResult>(this Func<Task<TSource>> source, | |
Func<TSource, Task<TResult>> selector) | |
{ | |
return async () => | |
{ | |
var sourceResult = await source(); | |
if (sourceResult == null) | |
return default(TResult); | |
return await selector.Invoke(sourceResult); | |
}; | |
} | |
public static Func<Task<TSource>> Aggregate<TSource>(this IEnumerable<Task<TSource>> source, | |
Func<Func<Task<TSource>>, Func<Task<TSource>>, Func<Task<TSource>>> func) | |
{ | |
return async () => | |
{ | |
return await source.Aggregate((task, task1) => | |
func.Invoke(() => task, () => task1)()); | |
}; | |
} | |
public static Func<Task<TSource>> AggregateWhile<TSource>(this IEnumerable<Task<TSource>> source, | |
Func<Func<Task<TSource>>, Func<Task<TSource>>, Func<Task<TSource>>> func, Func<TSource, bool> predicate) | |
{ | |
return async () => | |
{ | |
Func<Task<TSource>> total = () => Task.FromResult(default(TSource)); | |
foreach (var task in source) | |
{ | |
var result = func.Invoke(total, () => task); | |
if (!predicate(await result())) | |
break; | |
total = result; | |
} | |
return await total.Invoke(); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment