using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Umbraco.Cms.Core.Composing { public sealed class LazyReadOnlyCollection : IReadOnlyCollection { private readonly Lazy> _lazyCollection; private int? _count; public LazyReadOnlyCollection(Lazy> lazyCollection) => _lazyCollection = lazyCollection; public LazyReadOnlyCollection(Func> lazyCollection) => _lazyCollection = new Lazy>(lazyCollection); public IEnumerable Value => EnsureCollection(); private IEnumerable EnsureCollection() { if (_lazyCollection == null) { _count = 0; return Enumerable.Empty(); } IEnumerable val = _lazyCollection.Value; if (_count == null) { _count = val.Count(); } return val; } public int Count { get { EnsureCollection(); return _count.Value; } } public IEnumerator GetEnumerator() => Value.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }