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