using System.Collections; 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(); public int Count { get { EnsureCollection(); return _count.GetValueOrDefault(); } } public IEnumerator GetEnumerator() => Value.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private IEnumerable EnsureCollection() { if (_lazyCollection == null) { _count = 0; return Enumerable.Empty(); } IEnumerable val = _lazyCollection.Value; if (_count == null) { _count = val.Count(); } return val; } }