Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
  2. {
  3. if (source == null) throw new ArgumentNullException(nameof(source));
  4. if (action == null) throw new ArgumentNullException(nameof(action));
  5.  
  6. return _(); IEnumerable<T> _()
  7. {
  8. foreach (var element in source)
  9. {
  10. action(element);
  11. yield return element;
  12. }
  13. }
  14. }
  15.  
  16. public static class MyExtensions
  17. {
  18. public static IEnumerable<TResult> TrySelect<TSource, TResult, TException>(this IEnumerable<TSource> source,
  19. Func<TSource, TResult> selector,
  20. Action<TSource, TException> exceptionAction)
  21. where TException : Exception
  22. {
  23. foreach (var s in source)
  24. {
  25. TResult result = default(TResult);
  26. bool success = false;
  27. try
  28. {
  29. result = selector(s);
  30. success = true;
  31. }
  32. catch (TException ex)
  33. {
  34. exceptionAction(s,ex);
  35. }
  36. if (success)
  37. {
  38. // n.b. can't yield return inside a try block
  39. yield return result;
  40. }
  41. }
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement