2 using System.Collections.Generic;
5 using JetBrains.Annotations;
7 namespace FxSharp.Extensions
9 public static class EnumerableExtensions
17 public static IEnumerable<T> ToEnumerable<T>(
this T val)
29 public static Maybe<TSource> FirstOrNothing<TSource>(
30 [NotNull]
this IEnumerable<TSource> source,
31 [NotNull] Func<TSource, bool> predicate)
34 Ensure.NotNull(source,
"source");
35 Ensure.NotNull(predicate,
"predicate");
38 var enumerable = source as TSource[] ?? source.ToArray();
40 return !enumerable.Any(predicate)
41 ? Maybe.Nothing<TSource>()
42 : Maybe.Just(enumerable.FirstOrDefault(predicate));
51 public static Maybe<TSource> FirstOrNothing<TSource>(
52 [NotNull]
this IEnumerable<TSource> source)
55 Ensure.NotNull(source,
"source");
58 var enumerable = source as TSource[] ?? source.ToArray();
60 return enumerable.Any()
61 ? Maybe.Just(enumerable.FirstOrDefault())
62 : Maybe.Nothing<TSource>();
72 public static Maybe<TSource> LastOrNothing<TSource>(
73 [NotNull]
this IEnumerable<TSource> source)
76 Ensure.NotNull(source,
"source");
79 var enumerable = source as TSource[] ?? source.ToArray();
81 return enumerable.Any()
82 ? Maybe.Just(enumerable.LastOrDefault())
83 : Maybe.Nothing<TSource>();
97 public static Maybe<TSource> LastOrNothing<TSource>(
98 [NotNull]
this IEnumerable<TSource> source,
99 [NotNull] Func<TSource, bool> predicate)
102 Ensure.NotNull(source,
"source");
103 Ensure.NotNull(predicate,
"predicate");
106 var enumerable = source as TSource[] ?? source.ToArray();
108 return !enumerable.Any(predicate)
109 ? Maybe.Nothing<TSource>()
110 : Maybe.Just(enumerable.LastOrDefault(predicate));
126 public static Maybe<TSource> SingleOrNothing<TSource>(
127 [NotNull]
this IEnumerable<TSource> source,
128 [NotNull] Func<TSource, bool> predicate)
131 Ensure.NotNull(source,
"source");
132 Ensure.NotNull(predicate,
"predicate");
135 var filtered = source.Where(predicate);
137 using (var enumerator = filtered.GetEnumerator())
139 if (!enumerator.MoveNext())
return Maybe.Nothing<TSource>();
140 var result = enumerator.Current;
141 if (!enumerator.MoveNext())
return Maybe.Just(result);
144 return Maybe.Nothing<TSource>();
158 public static Maybe<TSource> SingleOrNothing<TSource>(
159 [NotNull]
this IEnumerable<TSource> source)
162 Ensure.NotNull(source,
"source");
165 using (var enumerator = source.GetEnumerator())
167 if (!enumerator.MoveNext())
return Maybe.Nothing<TSource>();
168 var result = enumerator.Current;
169 if (!enumerator.MoveNext())
return Maybe.Just(result);
171 return Maybe.Nothing<TSource>();