1
0

Using.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Generates a sequence that's dependent on a resource object whose lifetime is determined by the sequence usage
  11. /// duration.
  12. /// </summary>
  13. /// <typeparam name="TSource">Source element type.</typeparam>
  14. /// <typeparam name="TResource">Resource type.</typeparam>
  15. /// <param name="resourceFactory">Resource factory function.</param>
  16. /// <param name="enumerableFactory">Enumerable factory function, having access to the obtained resource.</param>
  17. /// <returns>Sequence whose use controls the lifetime of the associated obtained resource.</returns>
  18. public static IEnumerable<TSource> Using<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  19. {
  20. if (resourceFactory == null)
  21. {
  22. throw new ArgumentNullException(nameof(resourceFactory));
  23. }
  24. if (enumerableFactory == null)
  25. {
  26. throw new ArgumentNullException(nameof(enumerableFactory));
  27. }
  28. return Using_(resourceFactory, enumerableFactory);
  29. }
  30. private static IEnumerable<TSource> Using_<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  31. {
  32. using (var res = resourceFactory())
  33. {
  34. foreach (var item in enumerableFactory(res))
  35. {
  36. yield return item;
  37. }
  38. }
  39. }
  40. }
  41. }