Using.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. throw new ArgumentNullException(nameof(resourceFactory));
  22. if (enumerableFactory == null)
  23. throw new ArgumentNullException(nameof(enumerableFactory));
  24. return Using_(resourceFactory, enumerableFactory);
  25. }
  26. private static IEnumerable<TSource> Using_<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  27. {
  28. using (var res = resourceFactory())
  29. foreach (var item in enumerableFactory(res))
  30. yield return item;
  31. }
  32. }
  33. }