From 67fe9d46322ff275003af2c253f4d848ce1bc76f Mon Sep 17 00:00:00 2001 From: David Hall Date: Fri, 12 Jan 2018 11:39:58 -0700 Subject: [PATCH] Added default predicate value to Any(), new DefaultIfEmpty method and converted Count() method to switch. --- Core/BkwdComp/Linq.NET2.cs | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/Core/BkwdComp/Linq.NET2.cs b/Core/BkwdComp/Linq.NET2.cs index 1aebb845..65c3ada4 100644 --- a/Core/BkwdComp/Linq.NET2.cs +++ b/Core/BkwdComp/Linq.NET2.cs @@ -26,12 +26,11 @@ namespace System.Linq /// An whose elements to apply the predicate to. /// A function to test each element for a condition. /// true if any elements in the source sequence pass the test in the specified predicate; otherwise, false. - public static bool Any(this IEnumerable source, Func predicate) + public static bool Any(this IEnumerable source, Func predicate = null) { if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); foreach (TSource element in source) - if (predicate(element)) return true; + if (predicate == null || predicate(element)) return true; return false; } @@ -62,13 +61,44 @@ namespace System.Linq /// A sequence that contains elements to be counted. /// The number of elements in the input sequence. public static int Count(this IEnumerable source) + { + switch (source) + { + case null: + throw new ArgumentNullException(nameof(source)); + case ICollection c: + return c.Count; + case ICollection ngc: + return ngc.Count; + default: + var i = 0; + foreach (var e in source) i++; + return i; + } + } + + /// Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty. + /// The type of the elements of . + /// The sequence to return the specified value for if it is empty. + /// The value to return if the sequence is empty. This value defaults to . + /// An that contains if source is empty; otherwise, source. + public static IEnumerable DefaultIfEmpty(this IEnumerable source, TSource defaultValue = default(TSource)) { if (source == null) throw new ArgumentNullException(nameof(source)); - if (source is ICollection c) return c.Count; - if (source is ICollection ngc) return ngc.Count; - var i = 0; - foreach (var e in source) i++; - return i; + using (var e = source.GetEnumerator()) + { + if (e.MoveNext()) + { + do + { + yield return e.Current; + } while (e.MoveNext()); + } + else + { + yield return defaultValue; + } + } } /// Returns distinct elements from a sequence by using the default equality comparer to compare values.