3
#region License, Terms and Author(s)
6
// Copyright (c) 2007-9 Atif Aziz, Joseph Albahari. All rights reserved.
10
// Atif Aziz, http://www.raboof.com
12
// This library is free software; you can redistribute it and/or modify it
13
// under the terms of the New BSD License, a copy of which should have
14
// been delivered along with this distribution.
16
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
19
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
using System.Collections;
32
using System.Collections.Generic;
33
using System.Diagnostics;
34
using System.Globalization;
35
using Newtonsoft.Json.Serialization;
37
namespace Newtonsoft.Json.Utilities.LinqBridge
40
/// Provides a set of static (Shared in Visual Basic) methods for
41
/// querying objects that implement <see cref="IEnumerable{T}" />.
43
internal static partial class Enumerable
46
/// Returns the input typed as <see cref="IEnumerable{T}"/>.
49
public static IEnumerable<TSource> AsEnumerable<TSource>(IEnumerable<TSource> source)
55
/// Returns an empty <see cref="IEnumerable{T}"/> that has the
56
/// specified type argument.
59
public static IEnumerable<TResult> Empty<TResult>()
61
return Sequence<TResult>.Empty;
65
/// Converts the elements of an <see cref="IEnumerable"/> to the
69
public static IEnumerable<TResult> Cast<TResult>(
70
this IEnumerable source)
72
CheckNotNull(source, "source");
74
return CastYield<TResult>(source);
77
private static IEnumerable<TResult> CastYield<TResult>(
80
foreach (var item in source)
81
yield return (TResult) item;
85
/// Filters the elements of an <see cref="IEnumerable"/> based on a specified type.
88
public static IEnumerable<TResult> OfType<TResult>(
89
this IEnumerable source)
91
CheckNotNull(source, "source");
93
return OfTypeYield<TResult>(source);
96
private static IEnumerable<TResult> OfTypeYield<TResult>(
99
foreach (var item in source)
101
yield return (TResult) item;
105
/// Generates a sequence of integral numbers within a specified range.
107
/// <param name="start">The value of the first integer in the sequence.</param>
108
/// <param name="count">The number of sequential integers to generate.</param>
110
public static IEnumerable<int> Range(int start, int count)
113
throw new ArgumentOutOfRangeException("count", count, null);
115
var end = (long) start + count;
116
if (end - 1 >= int.MaxValue)
117
throw new ArgumentOutOfRangeException("count", count, null);
119
return RangeYield(start, end);
122
private static IEnumerable<int> RangeYield(int start, long end)
124
for (var i = start; i < end; i++)
129
/// Generates a sequence that contains one repeated value.
132
public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
134
if (count < 0) throw new ArgumentOutOfRangeException("count", count, null);
136
return RepeatYield(element, count);
139
private static IEnumerable<TResult> RepeatYield<TResult>(TResult element, int count)
141
for (var i = 0; i < count; i++)
142
yield return element;
146
/// Filters a sequence of values based on a predicate.
149
public static IEnumerable<TSource> Where<TSource>(
150
this IEnumerable<TSource> source,
151
Func<TSource, bool> predicate)
153
CheckNotNull(predicate, "predicate");
155
return source.Where((item, i) => predicate(item));
159
/// Filters a sequence of values based on a predicate.
160
/// Each element's index is used in the logic of the predicate function.
163
public static IEnumerable<TSource> Where<TSource>(
164
this IEnumerable<TSource> source,
165
Func<TSource, int, bool> predicate)
167
CheckNotNull(source, "source");
168
CheckNotNull(predicate, "predicate");
170
return WhereYield(source, predicate);
173
private static IEnumerable<TSource> WhereYield<TSource>(
174
IEnumerable<TSource> source,
175
Func<TSource, int, bool> predicate)
178
foreach (var item in source)
179
if (predicate(item, i++))
184
/// Projects each element of a sequence into a new form.
187
public static IEnumerable<TResult> Select<TSource, TResult>(
188
this IEnumerable<TSource> source,
189
Func<TSource, TResult> selector)
191
CheckNotNull(selector, "selector");
193
return source.Select((item, i) => selector(item));
197
/// Projects each element of a sequence into a new form by
198
/// incorporating the element's index.
201
public static IEnumerable<TResult> Select<TSource, TResult>(
202
this IEnumerable<TSource> source,
203
Func<TSource, int, TResult> selector)
205
CheckNotNull(source, "source");
206
CheckNotNull(selector, "selector");
208
return SelectYield(source, selector);
211
private static IEnumerable<TResult> SelectYield<TSource, TResult>(
212
IEnumerable<TSource> source,
213
Func<TSource, int, TResult> selector)
216
foreach (var item in source)
217
yield return selector(item, i++);
221
/// Projects each element of a sequence to an <see cref="IEnumerable{T}" />
222
/// and flattens the resulting sequences into one sequence.
225
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
226
this IEnumerable<TSource> source,
227
Func<TSource, IEnumerable<TResult>> selector)
229
CheckNotNull(selector, "selector");
231
return source.SelectMany((item, i) => selector(item));
235
/// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
236
/// and flattens the resulting sequences into one sequence. The
237
/// index of each source element is used in the projected form of
241
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
242
this IEnumerable<TSource> source,
243
Func<TSource, int, IEnumerable<TResult>> selector)
245
CheckNotNull(selector, "selector");
247
return source.SelectMany(selector, (item, subitem) => subitem);
251
/// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
252
/// flattens the resulting sequences into one sequence, and invokes
253
/// a result selector function on each element therein.
256
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
257
this IEnumerable<TSource> source,
258
Func<TSource, IEnumerable<TCollection>> collectionSelector,
259
Func<TSource, TCollection, TResult> resultSelector)
261
CheckNotNull(collectionSelector, "collectionSelector");
263
return source.SelectMany((item, i) => collectionSelector(item), resultSelector);
267
/// Projects each element of a sequence to an <see cref="IEnumerable{T}" />,
268
/// flattens the resulting sequences into one sequence, and invokes
269
/// a result selector function on each element therein. The index of
270
/// each source element is used in the intermediate projected form
274
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
275
this IEnumerable<TSource> source,
276
Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
277
Func<TSource, TCollection, TResult> resultSelector)
279
CheckNotNull(source, "source");
280
CheckNotNull(collectionSelector, "collectionSelector");
281
CheckNotNull(resultSelector, "resultSelector");
283
return SelectManyYield(source, collectionSelector, resultSelector);
286
private static IEnumerable<TResult> SelectManyYield<TSource, TCollection, TResult>(
287
this IEnumerable<TSource> source,
288
Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
289
Func<TSource, TCollection, TResult> resultSelector)
292
foreach (var item in source)
293
foreach (var subitem in collectionSelector(item, i++))
294
yield return resultSelector(item, subitem);
298
/// Returns elements from a sequence as long as a specified condition is true.
301
public static IEnumerable<TSource> TakeWhile<TSource>(
302
this IEnumerable<TSource> source,
303
Func<TSource, bool> predicate)
305
CheckNotNull(predicate, "predicate");
307
return source.TakeWhile((item, i) => predicate(item));
311
/// Returns elements from a sequence as long as a specified condition is true.
312
/// The element's index is used in the logic of the predicate function.
315
public static IEnumerable<TSource> TakeWhile<TSource>(
316
this IEnumerable<TSource> source,
317
Func<TSource, int, bool> predicate)
319
CheckNotNull(source, "source");
320
CheckNotNull(predicate, "predicate");
322
return TakeWhileYield(source, predicate);
325
private static IEnumerable<TSource> TakeWhileYield<TSource>(
326
this IEnumerable<TSource> source,
327
Func<TSource, int, bool> predicate)
330
foreach (var item in source)
331
if (predicate(item, i++))
337
private static class Futures<T>
339
public static readonly Func<T> Default = () => default(T);
340
public static readonly Func<T> Undefined = () => { throw new InvalidOperationException(); };
344
/// Base implementation of First operator.
347
private static TSource FirstImpl<TSource>(
348
this IEnumerable<TSource> source,
351
CheckNotNull(source, "source");
352
Debug.Assert(empty != null);
354
var list = source as IList<TSource>; // optimized case for lists
356
return list.Count > 0 ? list[0] : empty();
358
using (var e = source.GetEnumerator()) // fallback for enumeration
359
return e.MoveNext() ? e.Current : empty();
363
/// Returns the first element of a sequence.
366
public static TSource First<TSource>(
367
this IEnumerable<TSource> source)
369
return source.FirstImpl(Futures<TSource>.Undefined);
373
/// Returns the first element in a sequence that satisfies a specified condition.
376
public static TSource First<TSource>(
377
this IEnumerable<TSource> source,
378
Func<TSource, bool> predicate)
380
return First(source.Where(predicate));
384
/// Returns the first element of a sequence, or a default value if
385
/// the sequence contains no elements.
388
public static TSource FirstOrDefault<TSource>(
389
this IEnumerable<TSource> source)
391
return source.FirstImpl(Futures<TSource>.Default);
395
/// Returns the first element of the sequence that satisfies a
396
/// condition or a default value if no such element is found.
399
public static TSource FirstOrDefault<TSource>(
400
this IEnumerable<TSource> source,
401
Func<TSource, bool> predicate)
403
return FirstOrDefault(source.Where(predicate));
407
/// Base implementation of Last operator.
410
private static TSource LastImpl<TSource>(
411
this IEnumerable<TSource> source,
414
CheckNotNull(source, "source");
416
var list = source as IList<TSource>; // optimized case for lists
418
return list.Count > 0 ? list[list.Count - 1] : empty();
420
using (var e = source.GetEnumerator())
425
var last = e.Current;
434
/// Returns the last element of a sequence.
436
public static TSource Last<TSource>(
437
this IEnumerable<TSource> source)
439
return source.LastImpl(Futures<TSource>.Undefined);
443
/// Returns the last element of a sequence that satisfies a
444
/// specified condition.
447
public static TSource Last<TSource>(
448
this IEnumerable<TSource> source,
449
Func<TSource, bool> predicate)
451
return Last(source.Where(predicate));
455
/// Returns the last element of a sequence, or a default value if
456
/// the sequence contains no elements.
459
public static TSource LastOrDefault<TSource>(
460
this IEnumerable<TSource> source)
462
return source.LastImpl(Futures<TSource>.Default);
466
/// Returns the last element of a sequence that satisfies a
467
/// condition or a default value if no such element is found.
470
public static TSource LastOrDefault<TSource>(
471
this IEnumerable<TSource> source,
472
Func<TSource, bool> predicate)
474
return LastOrDefault(source.Where(predicate));
478
/// Base implementation of Single operator.
481
private static TSource SingleImpl<TSource>(
482
this IEnumerable<TSource> source,
485
CheckNotNull(source, "source");
487
using (var e = source.GetEnumerator())
491
var single = e.Current;
495
throw new InvalidOperationException();
503
/// Returns the only element of a sequence, and throws an exception
504
/// if there is not exactly one element in the sequence.
507
public static TSource Single<TSource>(
508
this IEnumerable<TSource> source)
510
return source.SingleImpl(Futures<TSource>.Undefined);
514
/// Returns the only element of a sequence that satisfies a
515
/// specified condition, and throws an exception if more than one
516
/// such element exists.
519
public static TSource Single<TSource>(
520
this IEnumerable<TSource> source,
521
Func<TSource, bool> predicate)
523
return Single(source.Where(predicate));
527
/// Returns the only element of a sequence, or a default value if
528
/// the sequence is empty; this method throws an exception if there
529
/// is more than one element in the sequence.
532
public static TSource SingleOrDefault<TSource>(
533
this IEnumerable<TSource> source)
535
return source.SingleImpl(Futures<TSource>.Default);
539
/// Returns the only element of a sequence that satisfies a
540
/// specified condition or a default value if no such element
541
/// exists; this method throws an exception if more than one element
542
/// satisfies the condition.
545
public static TSource SingleOrDefault<TSource>(
546
this IEnumerable<TSource> source,
547
Func<TSource, bool> predicate)
549
return SingleOrDefault(source.Where(predicate));
553
/// Returns the element at a specified index in a sequence.
556
public static TSource ElementAt<TSource>(
557
this IEnumerable<TSource> source,
560
CheckNotNull(source, "source");
563
throw new ArgumentOutOfRangeException("index", index, null);
565
var list = source as IList<TSource>;
571
return source.SkipWhile((item, i) => i < index).First();
573
catch (InvalidOperationException) // if thrown by First
575
throw new ArgumentOutOfRangeException("index", index, null);
580
/// Returns the element at a specified index in a sequence or a
581
/// default value if the index is out of range.
584
public static TSource ElementAtOrDefault<TSource>(
585
this IEnumerable<TSource> source,
588
CheckNotNull(source, "source");
591
return default(TSource);
593
var list = source as IList<TSource>;
595
return index < list.Count ? list[index] : default(TSource);
597
return source.SkipWhile((item, i) => i < index).FirstOrDefault();
601
/// Inverts the order of the elements in a sequence.
604
public static IEnumerable<TSource> Reverse<TSource>(
605
this IEnumerable<TSource> source)
607
CheckNotNull(source, "source");
609
return ReverseYield(source);
612
private static IEnumerable<TSource> ReverseYield<TSource>(IEnumerable<TSource> source)
614
var stack = new Stack<TSource>();
615
foreach (var item in source)
618
foreach (var item in stack)
623
/// Returns a specified number of contiguous elements from the start
627
public static IEnumerable<TSource> Take<TSource>(
628
this IEnumerable<TSource> source,
631
return source.Where((item, i) => i < count);
635
/// Bypasses a specified number of elements in a sequence and then
636
/// returns the remaining elements.
639
public static IEnumerable<TSource> Skip<TSource>(
640
this IEnumerable<TSource> source,
643
return source.Where((item, i) => i >= count);
647
/// Bypasses elements in a sequence as long as a specified condition
648
/// is true and then returns the remaining elements.
651
public static IEnumerable<TSource> SkipWhile<TSource>(
652
this IEnumerable<TSource> source,
653
Func<TSource, bool> predicate)
655
CheckNotNull(predicate, "predicate");
657
return source.SkipWhile((item, i) => predicate(item));
661
/// Bypasses elements in a sequence as long as a specified condition
662
/// is true and then returns the remaining elements. The element's
663
/// index is used in the logic of the predicate function.
666
public static IEnumerable<TSource> SkipWhile<TSource>(
667
this IEnumerable<TSource> source,
668
Func<TSource, int, bool> predicate)
670
CheckNotNull(source, "source");
671
CheckNotNull(predicate, "predicate");
673
return SkipWhileYield(source, predicate);
676
private static IEnumerable<TSource> SkipWhileYield<TSource>(
677
IEnumerable<TSource> source,
678
Func<TSource, int, bool> predicate)
680
using (var e = source.GetEnumerator())
682
for (var i = 0;; i++)
687
if (!predicate(e.Current, i))
693
yield return e.Current;
694
} while (e.MoveNext());
699
/// Returns the number of elements in a sequence.
702
public static int Count<TSource>(
703
this IEnumerable<TSource> source)
705
CheckNotNull(source, "source");
707
var collection = source as ICollection;
708
return collection != null
710
: source.Aggregate(0, (count, item) => checked(count + 1));
714
/// Returns a number that represents how many elements in the
715
/// specified sequence satisfy a condition.
718
public static int Count<TSource>(
719
this IEnumerable<TSource> source,
720
Func<TSource, bool> predicate)
722
return Count(source.Where(predicate));
726
/// Returns an <see cref="Int64"/> that represents the total number
727
/// of elements in a sequence.
730
public static long LongCount<TSource>(
731
this IEnumerable<TSource> source)
733
CheckNotNull(source, "source");
735
var array = source as Array;
738
: source.Aggregate(0L, (count, item) => count + 1);
742
/// Returns an <see cref="Int64"/> that represents how many elements
743
/// in a sequence satisfy a condition.
746
public static long LongCount<TSource>(
747
this IEnumerable<TSource> source,
748
Func<TSource, bool> predicate)
750
return LongCount(source.Where(predicate));
754
/// Concatenates two sequences.
757
public static IEnumerable<TSource> Concat<TSource>(
758
this IEnumerable<TSource> first,
759
IEnumerable<TSource> second)
761
CheckNotNull(first, "first");
762
CheckNotNull(second, "second");
764
return ConcatYield(first, second);
767
private static IEnumerable<TSource> ConcatYield<TSource>(
768
IEnumerable<TSource> first,
769
IEnumerable<TSource> second)
771
foreach (var item in first)
774
foreach (var item in second)
779
/// Creates a <see cref="List{T}"/> from an <see cref="IEnumerable{T}"/>.
782
public static List<TSource> ToList<TSource>(
783
this IEnumerable<TSource> source)
785
CheckNotNull(source, "source");
787
return new List<TSource>(source);
791
/// Creates an array from an <see cref="IEnumerable{T}"/>.
794
public static TSource[] ToArray<TSource>(
795
this IEnumerable<TSource> source)
797
return source.ToList().ToArray();
801
/// Returns distinct elements from a sequence by using the default
802
/// equality comparer to compare values.
805
public static IEnumerable<TSource> Distinct<TSource>(
806
this IEnumerable<TSource> source)
808
return Distinct(source, /* comparer */ null);
812
/// Returns distinct elements from a sequence by using a specified
813
/// <see cref="IEqualityComparer{T}"/> to compare values.
816
public static IEnumerable<TSource> Distinct<TSource>(
817
this IEnumerable<TSource> source,
818
IEqualityComparer<TSource> comparer)
820
CheckNotNull(source, "source");
822
return DistinctYield(source, comparer);
825
private static IEnumerable<TSource> DistinctYield<TSource>(
826
IEnumerable<TSource> source,
827
IEqualityComparer<TSource> comparer)
829
var set = new Dictionary<TSource, object>(comparer);
832
foreach (var item in source)
842
if (set.ContainsKey(item))
852
/// Creates a <see cref="Lookup{TKey,TElement}" /> from an
853
/// <see cref="IEnumerable{T}" /> according to a specified key
854
/// selector function.
857
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
858
this IEnumerable<TSource> source,
859
Func<TSource, TKey> keySelector)
861
return ToLookup(source, keySelector, e => e, /* comparer */ null);
865
/// Creates a <see cref="Lookup{TKey,TElement}" /> from an
866
/// <see cref="IEnumerable{T}" /> according to a specified key
867
/// selector function and a key comparer.
870
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
871
this IEnumerable<TSource> source,
872
Func<TSource, TKey> keySelector,
873
IEqualityComparer<TKey> comparer)
875
return ToLookup(source, keySelector, e => e, comparer);
879
/// Creates a <see cref="Lookup{TKey,TElement}" /> from an
880
/// <see cref="IEnumerable{T}" /> according to specified key
881
/// and element selector functions.
884
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
885
this IEnumerable<TSource> source,
886
Func<TSource, TKey> keySelector,
887
Func<TSource, TElement> elementSelector)
889
return ToLookup(source, keySelector, elementSelector, /* comparer */ null);
893
/// Creates a <see cref="Lookup{TKey,TElement}" /> from an
894
/// <see cref="IEnumerable{T}" /> according to a specified key
895
/// selector function, a comparer and an element selector function.
898
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
899
this IEnumerable<TSource> source,
900
Func<TSource, TKey> keySelector,
901
Func<TSource, TElement> elementSelector,
902
IEqualityComparer<TKey> comparer)
904
CheckNotNull(source, "source");
905
CheckNotNull(keySelector, "keySelector");
906
CheckNotNull(elementSelector, "elementSelector");
908
var lookup = new Lookup<TKey, TElement>(comparer);
910
foreach (var item in source)
912
var key = keySelector(item);
914
var grouping = (Grouping<TKey, TElement>) lookup.Find(key);
915
if (grouping == null)
917
grouping = new Grouping<TKey, TElement>(key);
918
lookup.Add(grouping);
921
grouping.Add(elementSelector(item));
928
/// Groups the elements of a sequence according to a specified key
929
/// selector function.
932
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
933
this IEnumerable<TSource> source,
934
Func<TSource, TKey> keySelector)
936
return GroupBy(source, keySelector, /* comparer */ null);
940
/// Groups the elements of a sequence according to a specified key
941
/// selector function and compares the keys by using a specified
945
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
946
this IEnumerable<TSource> source,
947
Func<TSource, TKey> keySelector,
948
IEqualityComparer<TKey> comparer)
950
return GroupBy(source, keySelector, e => e, comparer);
954
/// Groups the elements of a sequence according to a specified key
955
/// selector function and projects the elements for each group by
956
/// using a specified function.
959
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
960
this IEnumerable<TSource> source,
961
Func<TSource, TKey> keySelector,
962
Func<TSource, TElement> elementSelector)
964
return GroupBy(source, keySelector, elementSelector, /* comparer */ null);
968
/// Groups the elements of a sequence according to a specified key
969
/// selector function and creates a result value from each group and
973
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
974
this IEnumerable<TSource> source,
975
Func<TSource, TKey> keySelector,
976
Func<TSource, TElement> elementSelector,
977
IEqualityComparer<TKey> comparer)
979
CheckNotNull(source, "source");
980
CheckNotNull(keySelector, "keySelector");
981
CheckNotNull(elementSelector, "elementSelector");
983
return ToLookup(source, keySelector, elementSelector, comparer);
987
/// Groups the elements of a sequence according to a key selector
988
/// function. The keys are compared by using a comparer and each
989
/// group's elements are projected by using a specified function.
992
public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
993
this IEnumerable<TSource> source,
994
Func<TSource, TKey> keySelector,
995
Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
997
return GroupBy(source, keySelector, resultSelector, /* comparer */ null);
1001
/// Groups the elements of a sequence according to a specified key
1002
/// selector function and creates a result value from each group and
1003
/// its key. The elements of each group are projected by using a
1004
/// specified function.
1007
public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
1008
this IEnumerable<TSource> source,
1009
Func<TSource, TKey> keySelector,
1010
Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
1011
IEqualityComparer<TKey> comparer)
1013
CheckNotNull(source, "source");
1014
CheckNotNull(keySelector, "keySelector");
1015
CheckNotNull(resultSelector, "resultSelector");
1017
return ToLookup(source, keySelector, comparer).Select(g => resultSelector(g.Key, g));
1021
/// Groups the elements of a sequence according to a specified key
1022
/// selector function and creates a result value from each group and
1023
/// its key. The keys are compared by using a specified comparer.
1026
public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
1027
this IEnumerable<TSource> source,
1028
Func<TSource, TKey> keySelector,
1029
Func<TSource, TElement> elementSelector,
1030
Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
1032
return GroupBy(source, keySelector, elementSelector, resultSelector, /* comparer */ null);
1036
/// Groups the elements of a sequence according to a specified key
1037
/// selector function and creates a result value from each group and
1038
/// its key. Key values are compared by using a specified comparer,
1039
/// and the elements of each group are projected by using a
1040
/// specified function.
1043
public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(
1044
this IEnumerable<TSource> source,
1045
Func<TSource, TKey> keySelector,
1046
Func<TSource, TElement> elementSelector,
1047
Func<TKey, IEnumerable<TElement>, TResult> resultSelector,
1048
IEqualityComparer<TKey> comparer)
1050
CheckNotNull(source, "source");
1051
CheckNotNull(keySelector, "keySelector");
1052
CheckNotNull(elementSelector, "elementSelector");
1053
CheckNotNull(resultSelector, "resultSelector");
1055
return ToLookup(source, keySelector, elementSelector, comparer)
1056
.Select(g => resultSelector(g.Key, g));
1060
/// Applies an accumulator function over a sequence.
1063
public static TSource Aggregate<TSource>(
1064
this IEnumerable<TSource> source,
1065
Func<TSource, TSource, TSource> func)
1067
CheckNotNull(source, "source");
1068
CheckNotNull(func, "func");
1070
using (var e = source.GetEnumerator())
1073
throw new InvalidOperationException();
1075
return e.Renumerable().Skip(1).Aggregate(e.Current, func);
1080
/// Applies an accumulator function over a sequence. The specified
1081
/// seed value is used as the initial accumulator value.
1084
public static TAccumulate Aggregate<TSource, TAccumulate>(
1085
this IEnumerable<TSource> source,
1087
Func<TAccumulate, TSource, TAccumulate> func)
1089
return Aggregate(source, seed, func, r => r);
1093
/// Applies an accumulator function over a sequence. The specified
1094
/// seed value is used as the initial accumulator value, and the
1095
/// specified function is used to select the result value.
1098
public static TResult Aggregate<TSource, TAccumulate, TResult>(
1099
this IEnumerable<TSource> source,
1101
Func<TAccumulate, TSource, TAccumulate> func,
1102
Func<TAccumulate, TResult> resultSelector)
1104
CheckNotNull(source, "source");
1105
CheckNotNull(func, "func");
1106
CheckNotNull(resultSelector, "resultSelector");
1110
foreach (var item in source)
1111
result = func(result, item);
1113
return resultSelector(result);
1117
/// Produces the set union of two sequences by using the default
1118
/// equality comparer.
1121
public static IEnumerable<TSource> Union<TSource>(
1122
this IEnumerable<TSource> first,
1123
IEnumerable<TSource> second)
1125
return Union(first, second, /* comparer */ null);
1129
/// Produces the set union of two sequences by using a specified
1130
/// <see cref="IEqualityComparer{T}" />.
1133
public static IEnumerable<TSource> Union<TSource>(
1134
this IEnumerable<TSource> first,
1135
IEnumerable<TSource> second,
1136
IEqualityComparer<TSource> comparer)
1138
return first.Concat(second).Distinct(comparer);
1142
/// Returns the elements of the specified sequence or the type
1143
/// parameter's default value in a singleton collection if the
1144
/// sequence is empty.
1147
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
1148
this IEnumerable<TSource> source)
1150
return source.DefaultIfEmpty(default(TSource));
1154
/// Returns the elements of the specified sequence or the specified
1155
/// value in a singleton collection if the sequence is empty.
1158
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
1159
this IEnumerable<TSource> source,
1160
TSource defaultValue)
1162
CheckNotNull(source, "source");
1164
return DefaultIfEmptyYield(source, defaultValue);
1167
private static IEnumerable<TSource> DefaultIfEmptyYield<TSource>(
1168
IEnumerable<TSource> source,
1169
TSource defaultValue)
1171
using (var e = source.GetEnumerator())
1174
yield return defaultValue;
1178
yield return e.Current;
1179
} while (e.MoveNext());
1184
/// Determines whether all elements of a sequence satisfy a condition.
1187
public static bool All<TSource>(
1188
this IEnumerable<TSource> source,
1189
Func<TSource, bool> predicate)
1191
CheckNotNull(source, "source");
1192
CheckNotNull(predicate, "predicate");
1194
foreach (var item in source)
1195
if (!predicate(item))
1202
/// Determines whether a sequence contains any elements.
1205
public static bool Any<TSource>(
1206
this IEnumerable<TSource> source)
1208
CheckNotNull(source, "source");
1210
using (var e = source.GetEnumerator())
1211
return e.MoveNext();
1215
/// Determines whether any element of a sequence satisfies a
1219
public static bool Any<TSource>(
1220
this IEnumerable<TSource> source,
1221
Func<TSource, bool> predicate)
1223
return source.Where(predicate).Any();
1227
/// Determines whether a sequence contains a specified element by
1228
/// using the default equality comparer.
1231
public static bool Contains<TSource>(
1232
this IEnumerable<TSource> source,
1235
return source.Contains(value, /* comparer */ null);
1239
/// Determines whether a sequence contains a specified element by
1240
/// using a specified <see cref="IEqualityComparer{T}" />.
1243
public static bool Contains<TSource>(
1244
this IEnumerable<TSource> source,
1246
IEqualityComparer<TSource> comparer)
1248
CheckNotNull(source, "source");
1250
if (comparer == null)
1252
var collection = source as ICollection<TSource>;
1253
if (collection != null)
1254
return collection.Contains(value);
1257
comparer = comparer ?? EqualityComparer<TSource>.Default;
1258
return source.Any(item => comparer.Equals(item, value));
1262
/// Determines whether two sequences are equal by comparing the
1263
/// elements by using the default equality comparer for their type.
1266
public static bool SequenceEqual<TSource>(
1267
this IEnumerable<TSource> first,
1268
IEnumerable<TSource> second)
1270
return first.SequenceEqual(second, /* comparer */ null);
1274
/// Determines whether two sequences are equal by comparing their
1275
/// elements by using a specified <see cref="IEqualityComparer{T}" />.
1278
public static bool SequenceEqual<TSource>(
1279
this IEnumerable<TSource> first,
1280
IEnumerable<TSource> second,
1281
IEqualityComparer<TSource> comparer)
1283
CheckNotNull(first, "frist");
1284
CheckNotNull(second, "second");
1286
comparer = comparer ?? EqualityComparer<TSource>.Default;
1288
using (IEnumerator<TSource> lhs = first.GetEnumerator(),
1289
rhs = second.GetEnumerator())
1293
if (!lhs.MoveNext())
1294
return !rhs.MoveNext();
1296
if (!rhs.MoveNext())
1298
} while (comparer.Equals(lhs.Current, rhs.Current));
1305
/// Base implementation for Min/Max operator.
1308
private static TSource MinMaxImpl<TSource>(
1309
this IEnumerable<TSource> source,
1310
Func<TSource, TSource, bool> lesser)
1312
CheckNotNull(source, "source");
1313
Debug.Assert(lesser != null);
1315
return source.Aggregate((a, item) => lesser(a, item) ? a : item);
1319
/// Base implementation for Min/Max operator for nullable types.
1322
private static TSource? MinMaxImpl<TSource>(
1323
this IEnumerable<TSource?> source,
1324
TSource? seed, Func<TSource?, TSource?, bool> lesser) where TSource : struct
1326
CheckNotNull(source, "source");
1327
Debug.Assert(lesser != null);
1329
return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item);
1330
// == MinMaxImpl(Repeat<TSource?>(null, 1).Concat(source), lesser);
1334
/// Returns the minimum value in a generic sequence.
1337
public static TSource Min<TSource>(
1338
this IEnumerable<TSource> source)
1340
var comparer = Comparer<TSource>.Default;
1341
return source.MinMaxImpl((x, y) => comparer.Compare(x, y) < 0);
1345
/// Invokes a transform function on each element of a generic
1346
/// sequence and returns the minimum resulting value.
1349
public static TResult Min<TSource, TResult>(
1350
this IEnumerable<TSource> source,
1351
Func<TSource, TResult> selector)
1353
return source.Select(selector).Min();
1357
/// Returns the maximum value in a generic sequence.
1360
public static TSource Max<TSource>(
1361
this IEnumerable<TSource> source)
1363
var comparer = Comparer<TSource>.Default;
1364
return source.MinMaxImpl((x, y) => comparer.Compare(x, y) > 0);
1368
/// Invokes a transform function on each element of a generic
1369
/// sequence and returns the maximum resulting value.
1372
public static TResult Max<TSource, TResult>(
1373
this IEnumerable<TSource> source,
1374
Func<TSource, TResult> selector)
1376
return source.Select(selector).Max();
1380
/// Makes an enumerator seen as enumerable once more.
1383
/// The supplied enumerator must have been started. The first element
1384
/// returned is the element the enumerator was on when passed in.
1385
/// DO NOT use this method if the caller must be a generator. It is
1386
/// mostly safe among aggregate operations.
1389
private static IEnumerable<T> Renumerable<T>(this IEnumerator<T> e)
1391
Debug.Assert(e != null);
1395
yield return e.Current;
1396
} while (e.MoveNext());
1400
/// Sorts the elements of a sequence in ascending order according to a key.
1403
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
1404
this IEnumerable<TSource> source,
1405
Func<TSource, TKey> keySelector)
1407
return source.OrderBy(keySelector, /* comparer */ null);
1411
/// Sorts the elements of a sequence in ascending order by using a
1412
/// specified comparer.
1415
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
1416
this IEnumerable<TSource> source,
1417
Func<TSource, TKey> keySelector,
1418
IComparer<TKey> comparer)
1420
CheckNotNull(source, "source");
1421
CheckNotNull(keySelector, "keySelector");
1423
return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ false);
1427
/// Sorts the elements of a sequence in descending order according to a key.
1430
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
1431
this IEnumerable<TSource> source,
1432
Func<TSource, TKey> keySelector)
1434
return source.OrderByDescending(keySelector, /* comparer */ null);
1438
/// Sorts the elements of a sequence in descending order by using a
1439
/// specified comparer.
1442
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
1443
this IEnumerable<TSource> source,
1444
Func<TSource, TKey> keySelector,
1445
IComparer<TKey> comparer)
1447
CheckNotNull(source, "source");
1448
CheckNotNull(source, "keySelector");
1450
return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ true);
1454
/// Performs a subsequent ordering of the elements in a sequence in
1455
/// ascending order according to a key.
1458
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
1459
this IOrderedEnumerable<TSource> source,
1460
Func<TSource, TKey> keySelector)
1462
return source.ThenBy(keySelector, /* comparer */ null);
1466
/// Performs a subsequent ordering of the elements in a sequence in
1467
/// ascending order by using a specified comparer.
1470
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
1471
this IOrderedEnumerable<TSource> source,
1472
Func<TSource, TKey> keySelector,
1473
IComparer<TKey> comparer)
1475
CheckNotNull(source, "source");
1477
return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ false);
1481
/// Performs a subsequent ordering of the elements in a sequence in
1482
/// descending order, according to a key.
1485
public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
1486
this IOrderedEnumerable<TSource> source,
1487
Func<TSource, TKey> keySelector)
1489
return source.ThenByDescending(keySelector, /* comparer */ null);
1493
/// Performs a subsequent ordering of the elements in a sequence in
1494
/// descending order by using a specified comparer.
1497
public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
1498
this IOrderedEnumerable<TSource> source,
1499
Func<TSource, TKey> keySelector,
1500
IComparer<TKey> comparer)
1502
CheckNotNull(source, "source");
1504
return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ true);
1508
/// Base implementation for Intersect and Except operators.
1511
private static IEnumerable<TSource> IntersectExceptImpl<TSource>(
1512
this IEnumerable<TSource> first,
1513
IEnumerable<TSource> second,
1514
IEqualityComparer<TSource> comparer,
1517
CheckNotNull(first, "first");
1518
CheckNotNull(second, "second");
1520
var keys = new List<TSource>();
1521
var flags = new Dictionary<TSource, bool>(comparer);
1523
foreach (var item in first.Where(k => !flags.ContainsKey(k)))
1525
flags.Add(item, !flag);
1529
foreach (var item in second.Where(flags.ContainsKey))
1533
// As per docs, "the marked elements are yielded in the order in
1534
// which they were collected.
1537
return keys.Where(item => flags[item]);
1541
/// Produces the set intersection of two sequences by using the
1542
/// default equality comparer to compare values.
1545
public static IEnumerable<TSource> Intersect<TSource>(
1546
this IEnumerable<TSource> first,
1547
IEnumerable<TSource> second)
1549
return first.Intersect(second, /* comparer */ null);
1553
/// Produces the set intersection of two sequences by using the
1554
/// specified <see cref="IEqualityComparer{T}" /> to compare values.
1557
public static IEnumerable<TSource> Intersect<TSource>(
1558
this IEnumerable<TSource> first,
1559
IEnumerable<TSource> second,
1560
IEqualityComparer<TSource> comparer)
1562
return IntersectExceptImpl(first, second, comparer, /* flag */ true);
1566
/// Produces the set difference of two sequences by using the
1567
/// default equality comparer to compare values.
1570
public static IEnumerable<TSource> Except<TSource>(
1571
this IEnumerable<TSource> first,
1572
IEnumerable<TSource> second)
1574
return first.Except(second, /* comparer */ null);
1578
/// Produces the set difference of two sequences by using the
1579
/// specified <see cref="IEqualityComparer{T}" /> to compare values.
1582
public static IEnumerable<TSource> Except<TSource>(
1583
this IEnumerable<TSource> first,
1584
IEnumerable<TSource> second,
1585
IEqualityComparer<TSource> comparer)
1587
return IntersectExceptImpl(first, second, comparer, /* flag */ false);
1591
/// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
1592
/// <see cref="IEnumerable{T}" /> according to a specified key
1593
/// selector function.
1596
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
1597
this IEnumerable<TSource> source,
1598
Func<TSource, TKey> keySelector)
1600
return source.ToDictionary(keySelector, /* comparer */ null);
1604
/// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
1605
/// <see cref="IEnumerable{T}" /> according to a specified key
1606
/// selector function and key comparer.
1609
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
1610
this IEnumerable<TSource> source,
1611
Func<TSource, TKey> keySelector,
1612
IEqualityComparer<TKey> comparer)
1614
return source.ToDictionary(keySelector, e => e);
1618
/// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
1619
/// <see cref="IEnumerable{T}" /> according to specified key
1620
/// selector and element selector functions.
1623
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
1624
this IEnumerable<TSource> source,
1625
Func<TSource, TKey> keySelector,
1626
Func<TSource, TElement> elementSelector)
1628
return source.ToDictionary(keySelector, elementSelector, /* comparer */ null);
1632
/// Creates a <see cref="Dictionary{TKey,TValue}" /> from an
1633
/// <see cref="IEnumerable{T}" /> according to a specified key
1634
/// selector function, a comparer, and an element selector function.
1637
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
1638
this IEnumerable<TSource> source,
1639
Func<TSource, TKey> keySelector,
1640
Func<TSource, TElement> elementSelector,
1641
IEqualityComparer<TKey> comparer)
1643
CheckNotNull(source, "source");
1644
CheckNotNull(keySelector, "keySelector");
1645
CheckNotNull(elementSelector, "elementSelector");
1647
var dict = new Dictionary<TKey, TElement>(comparer);
1649
foreach (var item in source)
1652
// ToDictionary is meant to throw ArgumentNullException if
1653
// keySelector produces a key that is null and
1654
// Argument exception if keySelector produces duplicate keys
1655
// for two elements. Incidentally, the doucmentation for
1656
// IDictionary<TKey, TValue>.Add says that the Add method
1657
// throws the same exceptions under the same circumstances
1658
// so we don't need to do any additional checking or work
1659
// here and let the Add implementation do all the heavy
1663
dict.Add(keySelector(item), elementSelector(item));
1670
/// Correlates the elements of two sequences based on matching keys.
1671
/// The default equality comparer is used to compare keys.
1674
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
1675
this IEnumerable<TOuter> outer,
1676
IEnumerable<TInner> inner,
1677
Func<TOuter, TKey> outerKeySelector,
1678
Func<TInner, TKey> innerKeySelector,
1679
Func<TOuter, TInner, TResult> resultSelector)
1681
return outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
1685
/// Correlates the elements of two sequences based on matching keys.
1686
/// The default equality comparer is used to compare keys. A
1687
/// specified <see cref="IEqualityComparer{T}" /> is used to compare keys.
1690
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
1691
this IEnumerable<TOuter> outer,
1692
IEnumerable<TInner> inner,
1693
Func<TOuter, TKey> outerKeySelector,
1694
Func<TInner, TKey> innerKeySelector,
1695
Func<TOuter, TInner, TResult> resultSelector,
1696
IEqualityComparer<TKey> comparer)
1698
CheckNotNull(outer, "outer");
1699
CheckNotNull(inner, "inner");
1700
CheckNotNull(outerKeySelector, "outerKeySelector");
1701
CheckNotNull(innerKeySelector, "innerKeySelector");
1702
CheckNotNull(resultSelector, "resultSelector");
1704
var lookup = inner.ToLookup(innerKeySelector, comparer);
1708
from i in lookup[outerKeySelector(o)]
1709
select resultSelector(o, i);
1713
/// Correlates the elements of two sequences based on equality of
1714
/// keys and groups the results. The default equality comparer is
1715
/// used to compare keys.
1718
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
1719
this IEnumerable<TOuter> outer,
1720
IEnumerable<TInner> inner,
1721
Func<TOuter, TKey> outerKeySelector,
1722
Func<TInner, TKey> innerKeySelector,
1723
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
1725
return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
1729
/// Correlates the elements of two sequences based on equality of
1730
/// keys and groups the results. The default equality comparer is
1731
/// used to compare keys. A specified <see cref="IEqualityComparer{T}" />
1732
/// is used to compare keys.
1735
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
1736
this IEnumerable<TOuter> outer,
1737
IEnumerable<TInner> inner,
1738
Func<TOuter, TKey> outerKeySelector,
1739
Func<TInner, TKey> innerKeySelector,
1740
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
1741
IEqualityComparer<TKey> comparer)
1743
CheckNotNull(outer, "outer");
1744
CheckNotNull(inner, "inner");
1745
CheckNotNull(outerKeySelector, "outerKeySelector");
1746
CheckNotNull(innerKeySelector, "innerKeySelector");
1747
CheckNotNull(resultSelector, "resultSelector");
1749
var lookup = inner.ToLookup(innerKeySelector, comparer);
1750
return outer.Select(o => resultSelector(o, lookup[outerKeySelector(o)]));
1753
[DebuggerStepThrough]
1754
private static void CheckNotNull<T>(T value, string name) where T : class
1757
throw new ArgumentNullException(name);
1760
private static class Sequence<T>
1762
public static readonly IEnumerable<T> Empty = new T[0];
1765
private sealed class Grouping<K, V> : List<V>, IGrouping<K, V>
1767
internal Grouping(K key)
1772
public K Key { get; private set; }
1776
internal partial class Enumerable
1779
/// Computes the sum of a sequence of nullable <see cref="System.Int32" /> values.
1782
public static int Sum(
1783
this IEnumerable<int> source)
1785
CheckNotNull(source, "source");
1788
foreach (var num in source)
1789
sum = checked(sum + num);
1795
/// Computes the sum of a sequence of nullable <see cref="System.Int32" />
1796
/// values that are obtained by invoking a transform function on
1797
/// each element of the input sequence.
1800
public static int Sum<TSource>(
1801
this IEnumerable<TSource> source,
1802
Func<TSource, int> selector)
1804
return source.Select(selector).Sum();
1808
/// Computes the average of a sequence of nullable <see cref="System.Int32" /> values.
1811
public static double Average(
1812
this IEnumerable<int> source)
1814
CheckNotNull(source, "source");
1819
foreach (var num in source)
1827
throw new InvalidOperationException();
1829
return (double) sum/count;
1833
/// Computes the average of a sequence of nullable <see cref="System.Int32" /> values
1834
/// that are obtained by invoking a transform function on each
1835
/// element of the input sequence.
1838
public static double Average<TSource>(
1839
this IEnumerable<TSource> source,
1840
Func<TSource, int> selector)
1842
return source.Select(selector).Average();
1847
/// Computes the sum of a sequence of <see cref="System.Int32" /> values.
1850
public static int? Sum(
1851
this IEnumerable<int?> source)
1853
CheckNotNull(source, "source");
1856
foreach (var num in source)
1857
sum = checked(sum + (num ?? 0));
1863
/// Computes the sum of a sequence of <see cref="System.Int32" />
1864
/// values that are obtained by invoking a transform function on
1865
/// each element of the input sequence.
1868
public static int? Sum<TSource>(
1869
this IEnumerable<TSource> source,
1870
Func<TSource, int?> selector)
1872
return source.Select(selector).Sum();
1876
/// Computes the average of a sequence of <see cref="System.Int32" /> values.
1879
public static double? Average(
1880
this IEnumerable<int?> source)
1882
CheckNotNull(source, "source");
1887
foreach (var num in source.Where(n => n != null))
1897
return (double?) sum/count;
1901
/// Computes the average of a sequence of <see cref="System.Int32" /> values
1902
/// that are obtained by invoking a transform function on each
1903
/// element of the input sequence.
1906
public static double? Average<TSource>(
1907
this IEnumerable<TSource> source,
1908
Func<TSource, int?> selector)
1910
return source.Select(selector).Average();
1914
/// Returns the minimum value in a sequence of nullable
1915
/// <see cref="System.Int32" /> values.
1918
public static int? Min(
1919
this IEnumerable<int?> source)
1921
CheckNotNull(source, "source");
1923
return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
1927
/// Invokes a transform function on each element of a sequence and
1928
/// returns the minimum nullable <see cref="System.Int32" /> value.
1931
public static int? Min<TSource>(
1932
this IEnumerable<TSource> source,
1933
Func<TSource, int?> selector)
1935
return source.Select(selector).Min();
1939
/// Returns the maximum value in a sequence of nullable
1940
/// <see cref="System.Int32" /> values.
1943
public static int? Max(
1944
this IEnumerable<int?> source)
1946
CheckNotNull(source, "source");
1948
return MinMaxImpl(source.Where(x => x != null),
1949
null, (max, x) => x == null || (max != null && x.Value < max.Value));
1953
/// Invokes a transform function on each element of a sequence and
1954
/// returns the maximum nullable <see cref="System.Int32" /> value.
1957
public static int? Max<TSource>(
1958
this IEnumerable<TSource> source,
1959
Func<TSource, int?> selector)
1961
return source.Select(selector).Max();
1965
/// Computes the sum of a sequence of nullable <see cref="System.Int64" /> values.
1968
public static long Sum(
1969
this IEnumerable<long> source)
1971
CheckNotNull(source, "source");
1974
foreach (var num in source)
1975
sum = checked(sum + num);
1981
/// Computes the sum of a sequence of nullable <see cref="System.Int64" />
1982
/// values that are obtained by invoking a transform function on
1983
/// each element of the input sequence.
1986
public static long Sum<TSource>(
1987
this IEnumerable<TSource> source,
1988
Func<TSource, long> selector)
1990
return source.Select(selector).Sum();
1994
/// Computes the average of a sequence of nullable <see cref="System.Int64" /> values.
1997
public static double Average(
1998
this IEnumerable<long> source)
2000
CheckNotNull(source, "source");
2005
foreach (var num in source)
2013
throw new InvalidOperationException();
2015
return (double) sum/count;
2019
/// Computes the average of a sequence of nullable <see cref="System.Int64" /> values
2020
/// that are obtained by invoking a transform function on each
2021
/// element of the input sequence.
2024
public static double Average<TSource>(
2025
this IEnumerable<TSource> source,
2026
Func<TSource, long> selector)
2028
return source.Select(selector).Average();
2033
/// Computes the sum of a sequence of <see cref="System.Int64" /> values.
2036
public static long? Sum(
2037
this IEnumerable<long?> source)
2039
CheckNotNull(source, "source");
2042
foreach (var num in source)
2043
sum = checked(sum + (num ?? 0));
2049
/// Computes the sum of a sequence of <see cref="System.Int64" />
2050
/// values that are obtained by invoking a transform function on
2051
/// each element of the input sequence.
2054
public static long? Sum<TSource>(
2055
this IEnumerable<TSource> source,
2056
Func<TSource, long?> selector)
2058
return source.Select(selector).Sum();
2062
/// Computes the average of a sequence of <see cref="System.Int64" /> values.
2065
public static double? Average(
2066
this IEnumerable<long?> source)
2068
CheckNotNull(source, "source");
2073
foreach (var num in source.Where(n => n != null))
2083
return (double?) sum/count;
2087
/// Computes the average of a sequence of <see cref="System.Int64" /> values
2088
/// that are obtained by invoking a transform function on each
2089
/// element of the input sequence.
2092
public static double? Average<TSource>(
2093
this IEnumerable<TSource> source,
2094
Func<TSource, long?> selector)
2096
return source.Select(selector).Average();
2100
/// Returns the minimum value in a sequence of nullable
2101
/// <see cref="System.Int64" /> values.
2104
public static long? Min(
2105
this IEnumerable<long?> source)
2107
CheckNotNull(source, "source");
2109
return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
2113
/// Invokes a transform function on each element of a sequence and
2114
/// returns the minimum nullable <see cref="System.Int64" /> value.
2117
public static long? Min<TSource>(
2118
this IEnumerable<TSource> source,
2119
Func<TSource, long?> selector)
2121
return source.Select(selector).Min();
2125
/// Returns the maximum value in a sequence of nullable
2126
/// <see cref="System.Int64" /> values.
2129
public static long? Max(
2130
this IEnumerable<long?> source)
2132
CheckNotNull(source, "source");
2134
return MinMaxImpl(source.Where(x => x != null),
2135
null, (max, x) => x == null || (max != null && x.Value < max.Value));
2139
/// Invokes a transform function on each element of a sequence and
2140
/// returns the maximum nullable <see cref="System.Int64" /> value.
2143
public static long? Max<TSource>(
2144
this IEnumerable<TSource> source,
2145
Func<TSource, long?> selector)
2147
return source.Select(selector).Max();
2151
/// Computes the sum of a sequence of nullable <see cref="System.Single" /> values.
2154
public static float Sum(
2155
this IEnumerable<float> source)
2157
CheckNotNull(source, "source");
2160
foreach (var num in source)
2161
sum = checked(sum + num);
2167
/// Computes the sum of a sequence of nullable <see cref="System.Single" />
2168
/// values that are obtained by invoking a transform function on
2169
/// each element of the input sequence.
2172
public static float Sum<TSource>(
2173
this IEnumerable<TSource> source,
2174
Func<TSource, float> selector)
2176
return source.Select(selector).Sum();
2180
/// Computes the average of a sequence of nullable <see cref="System.Single" /> values.
2183
public static float Average(
2184
this IEnumerable<float> source)
2186
CheckNotNull(source, "source");
2191
foreach (var num in source)
2199
throw new InvalidOperationException();
2201
return (float) sum/count;
2205
/// Computes the average of a sequence of nullable <see cref="System.Single" /> values
2206
/// that are obtained by invoking a transform function on each
2207
/// element of the input sequence.
2210
public static float Average<TSource>(
2211
this IEnumerable<TSource> source,
2212
Func<TSource, float> selector)
2214
return source.Select(selector).Average();
2219
/// Computes the sum of a sequence of <see cref="System.Single" /> values.
2222
public static float? Sum(
2223
this IEnumerable<float?> source)
2225
CheckNotNull(source, "source");
2228
foreach (var num in source)
2229
sum = checked(sum + (num ?? 0));
2235
/// Computes the sum of a sequence of <see cref="System.Single" />
2236
/// values that are obtained by invoking a transform function on
2237
/// each element of the input sequence.
2240
public static float? Sum<TSource>(
2241
this IEnumerable<TSource> source,
2242
Func<TSource, float?> selector)
2244
return source.Select(selector).Sum();
2248
/// Computes the average of a sequence of <see cref="System.Single" /> values.
2251
public static float? Average(
2252
this IEnumerable<float?> source)
2254
CheckNotNull(source, "source");
2259
foreach (var num in source.Where(n => n != null))
2269
return (float?) sum/count;
2273
/// Computes the average of a sequence of <see cref="System.Single" /> values
2274
/// that are obtained by invoking a transform function on each
2275
/// element of the input sequence.
2278
public static float? Average<TSource>(
2279
this IEnumerable<TSource> source,
2280
Func<TSource, float?> selector)
2282
return source.Select(selector).Average();
2286
/// Returns the minimum value in a sequence of nullable
2287
/// <see cref="System.Single" /> values.
2290
public static float? Min(
2291
this IEnumerable<float?> source)
2293
CheckNotNull(source, "source");
2295
return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
2299
/// Invokes a transform function on each element of a sequence and
2300
/// returns the minimum nullable <see cref="System.Single" /> value.
2303
public static float? Min<TSource>(
2304
this IEnumerable<TSource> source,
2305
Func<TSource, float?> selector)
2307
return source.Select(selector).Min();
2311
/// Returns the maximum value in a sequence of nullable
2312
/// <see cref="System.Single" /> values.
2315
public static float? Max(
2316
this IEnumerable<float?> source)
2318
CheckNotNull(source, "source");
2320
return MinMaxImpl(source.Where(x => x != null),
2321
null, (max, x) => x == null || (max != null && x.Value < max.Value));
2325
/// Invokes a transform function on each element of a sequence and
2326
/// returns the maximum nullable <see cref="System.Single" /> value.
2329
public static float? Max<TSource>(
2330
this IEnumerable<TSource> source,
2331
Func<TSource, float?> selector)
2333
return source.Select(selector).Max();
2337
/// Computes the sum of a sequence of nullable <see cref="System.Double" /> values.
2340
public static double Sum(
2341
this IEnumerable<double> source)
2343
CheckNotNull(source, "source");
2346
foreach (var num in source)
2347
sum = checked(sum + num);
2353
/// Computes the sum of a sequence of nullable <see cref="System.Double" />
2354
/// values that are obtained by invoking a transform function on
2355
/// each element of the input sequence.
2358
public static double Sum<TSource>(
2359
this IEnumerable<TSource> source,
2360
Func<TSource, double> selector)
2362
return source.Select(selector).Sum();
2366
/// Computes the average of a sequence of nullable <see cref="System.Double" /> values.
2369
public static double Average(
2370
this IEnumerable<double> source)
2372
CheckNotNull(source, "source");
2377
foreach (var num in source)
2380
sum += (double) num;
2385
throw new InvalidOperationException();
2387
return (double) sum/count;
2391
/// Computes the average of a sequence of nullable <see cref="System.Double" /> values
2392
/// that are obtained by invoking a transform function on each
2393
/// element of the input sequence.
2396
public static double Average<TSource>(
2397
this IEnumerable<TSource> source,
2398
Func<TSource, double> selector)
2400
return source.Select(selector).Average();
2405
/// Computes the sum of a sequence of <see cref="System.Double" /> values.
2408
public static double? Sum(
2409
this IEnumerable<double?> source)
2411
CheckNotNull(source, "source");
2414
foreach (var num in source)
2415
sum = checked(sum + (num ?? 0));
2421
/// Computes the sum of a sequence of <see cref="System.Double" />
2422
/// values that are obtained by invoking a transform function on
2423
/// each element of the input sequence.
2426
public static double? Sum<TSource>(
2427
this IEnumerable<TSource> source,
2428
Func<TSource, double?> selector)
2430
return source.Select(selector).Sum();
2434
/// Computes the average of a sequence of <see cref="System.Double" /> values.
2437
public static double? Average(
2438
this IEnumerable<double?> source)
2440
CheckNotNull(source, "source");
2445
foreach (var num in source.Where(n => n != null))
2448
sum += (double) num;
2455
return (double?) sum/count;
2459
/// Computes the average of a sequence of <see cref="System.Double" /> values
2460
/// that are obtained by invoking a transform function on each
2461
/// element of the input sequence.
2464
public static double? Average<TSource>(
2465
this IEnumerable<TSource> source,
2466
Func<TSource, double?> selector)
2468
return source.Select(selector).Average();
2472
/// Returns the minimum value in a sequence of nullable
2473
/// <see cref="System.Double" /> values.
2476
public static double? Min(
2477
this IEnumerable<double?> source)
2479
CheckNotNull(source, "source");
2481
return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
2485
/// Invokes a transform function on each element of a sequence and
2486
/// returns the minimum nullable <see cref="System.Double" /> value.
2489
public static double? Min<TSource>(
2490
this IEnumerable<TSource> source,
2491
Func<TSource, double?> selector)
2493
return source.Select(selector).Min();
2497
/// Returns the maximum value in a sequence of nullable
2498
/// <see cref="System.Double" /> values.
2501
public static double? Max(
2502
this IEnumerable<double?> source)
2504
CheckNotNull(source, "source");
2506
return MinMaxImpl(source.Where(x => x != null),
2507
null, (max, x) => x == null || (max != null && x.Value < max.Value));
2511
/// Invokes a transform function on each element of a sequence and
2512
/// returns the maximum nullable <see cref="System.Double" /> value.
2515
public static double? Max<TSource>(
2516
this IEnumerable<TSource> source,
2517
Func<TSource, double?> selector)
2519
return source.Select(selector).Max();
2523
/// Computes the sum of a sequence of nullable <see cref="System.Decimal" /> values.
2526
public static decimal Sum(
2527
this IEnumerable<decimal> source)
2529
CheckNotNull(source, "source");
2532
foreach (var num in source)
2533
sum = checked(sum + num);
2539
/// Computes the sum of a sequence of nullable <see cref="System.Decimal" />
2540
/// values that are obtained by invoking a transform function on
2541
/// each element of the input sequence.
2544
public static decimal Sum<TSource>(
2545
this IEnumerable<TSource> source,
2546
Func<TSource, decimal> selector)
2548
return source.Select(selector).Sum();
2552
/// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values.
2555
public static decimal Average(
2556
this IEnumerable<decimal> source)
2558
CheckNotNull(source, "source");
2563
foreach (var num in source)
2566
sum += (decimal) num;
2571
throw new InvalidOperationException();
2573
return (decimal) sum/count;
2577
/// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values
2578
/// that are obtained by invoking a transform function on each
2579
/// element of the input sequence.
2582
public static decimal Average<TSource>(
2583
this IEnumerable<TSource> source,
2584
Func<TSource, decimal> selector)
2586
return source.Select(selector).Average();
2591
/// Computes the sum of a sequence of <see cref="System.Decimal" /> values.
2594
public static decimal? Sum(
2595
this IEnumerable<decimal?> source)
2597
CheckNotNull(source, "source");
2600
foreach (var num in source)
2601
sum = checked(sum + (num ?? 0));
2607
/// Computes the sum of a sequence of <see cref="System.Decimal" />
2608
/// values that are obtained by invoking a transform function on
2609
/// each element of the input sequence.
2612
public static decimal? Sum<TSource>(
2613
this IEnumerable<TSource> source,
2614
Func<TSource, decimal?> selector)
2616
return source.Select(selector).Sum();
2620
/// Computes the average of a sequence of <see cref="System.Decimal" /> values.
2623
public static decimal? Average(
2624
this IEnumerable<decimal?> source)
2626
CheckNotNull(source, "source");
2631
foreach (var num in source.Where(n => n != null))
2634
sum += (decimal) num;
2641
return (decimal?) sum/count;
2645
/// Computes the average of a sequence of <see cref="System.Decimal" /> values
2646
/// that are obtained by invoking a transform function on each
2647
/// element of the input sequence.
2650
public static decimal? Average<TSource>(
2651
this IEnumerable<TSource> source,
2652
Func<TSource, decimal?> selector)
2654
return source.Select(selector).Average();
2658
/// Returns the minimum value in a sequence of nullable
2659
/// <see cref="System.Decimal" /> values.
2662
public static decimal? Min(
2663
this IEnumerable<decimal?> source)
2665
CheckNotNull(source, "source");
2667
return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
2671
/// Invokes a transform function on each element of a sequence and
2672
/// returns the minimum nullable <see cref="System.Decimal" /> value.
2675
public static decimal? Min<TSource>(
2676
this IEnumerable<TSource> source,
2677
Func<TSource, decimal?> selector)
2679
return source.Select(selector).Min();
2683
/// Returns the maximum value in a sequence of nullable
2684
/// <see cref="System.Decimal" /> values.
2687
public static decimal? Max(
2688
this IEnumerable<decimal?> source)
2690
CheckNotNull(source, "source");
2692
return MinMaxImpl(source.Where(x => x != null),
2693
null, (max, x) => x == null || (max != null && x.Value < max.Value));
2697
/// Invokes a transform function on each element of a sequence and
2698
/// returns the maximum nullable <see cref="System.Decimal" /> value.
2701
public static decimal? Max<TSource>(
2702
this IEnumerable<TSource> source,
2703
Func<TSource, decimal?> selector)
2705
return source.Select(selector).Max();
2710
/// Represents a collection of objects that have a common key.
2712
internal partial interface IGrouping<TKey, TElement> : IEnumerable<TElement>
2715
/// Gets the key of the <see cref="IGrouping{TKey,TElement}" />.
2722
/// Defines an indexer, size property, and Boolean search method for
2723
/// data structures that map keys to <see cref="IEnumerable{T}"/>
2724
/// sequences of values.
2726
internal partial interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
2728
bool Contains(TKey key);
2730
IEnumerable<TElement> this[TKey key] { get; }
2734
/// Represents a sorted sequence.
2736
internal partial interface IOrderedEnumerable<TElement> : IEnumerable<TElement>
2739
/// Performs a subsequent ordering on the elements of an
2740
/// <see cref="IOrderedEnumerable{T}"/> according to a key.
2743
IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(
2744
Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
2748
/// Represents a collection of keys each mapped to one or more values.
2750
internal sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement>
2752
private readonly Dictionary<TKey, IGrouping<TKey, TElement>> _map;
2754
internal Lookup(IEqualityComparer<TKey> comparer)
2756
_map = new Dictionary<TKey, IGrouping<TKey, TElement>>(comparer);
2759
internal void Add(IGrouping<TKey, TElement> item)
2761
_map.Add(item.Key, item);
2764
internal IEnumerable<TElement> Find(TKey key)
2766
IGrouping<TKey, TElement> grouping;
2767
return _map.TryGetValue(key, out grouping) ? grouping : null;
2771
/// Gets the number of key/value collection pairs in the <see cref="Lookup{TKey,TElement}" />.
2776
get { return _map.Count; }
2780
/// Gets the collection of values indexed by the specified key.
2783
public IEnumerable<TElement> this[TKey key]
2787
IGrouping<TKey, TElement> result;
2788
return _map.TryGetValue(key, out result) ? result : Enumerable.Empty<TElement>();
2793
/// Determines whether a specified key is in the <see cref="Lookup{TKey,TElement}" />.
2796
public bool Contains(TKey key)
2798
return _map.ContainsKey(key);
2802
/// Applies a transform function to each key and its associated
2803
/// values and returns the results.
2806
public IEnumerable<TResult> ApplyResultSelector<TResult>(
2807
Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
2809
if (resultSelector == null)
2810
throw new ArgumentNullException("resultSelector");
2812
foreach (var pair in _map)
2813
yield return resultSelector(pair.Key, pair.Value);
2817
/// Returns a generic enumerator that iterates through the <see cref="Lookup{TKey,TElement}" />.
2820
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
2822
return _map.Values.GetEnumerator();
2825
IEnumerator IEnumerable.GetEnumerator()
2827
return GetEnumerator();
2831
internal sealed class OrderedEnumerable<T, K> : IOrderedEnumerable<T>
2833
private readonly IEnumerable<T> _source;
2834
private readonly List<Comparison<T>> _comparisons;
2836
public OrderedEnumerable(IEnumerable<T> source,
2837
Func<T, K> keySelector, IComparer<K> comparer, bool descending) :
2838
this(source, null, keySelector, comparer, descending)
2842
private OrderedEnumerable(IEnumerable<T> source, List<Comparison<T>> comparisons,
2843
Func<T, K> keySelector, IComparer<K> comparer, bool descending)
2845
if (source == null) throw new ArgumentNullException("source");
2846
if (keySelector == null) throw new ArgumentNullException("keySelector");
2850
comparer = comparer ?? Comparer<K>.Default;
2852
if (comparisons == null)
2853
comparisons = new List<Comparison<T>>( /* capacity */ 4);
2855
comparisons.Add((x, y)
2856
=> (descending ? -1 : 1)*comparer.Compare(keySelector(x), keySelector(y)));
2858
_comparisons = comparisons;
2861
public IOrderedEnumerable<T> CreateOrderedEnumerable<KK>(
2862
Func<T, KK> keySelector, IComparer<KK> comparer, bool descending)
2864
return new OrderedEnumerable<T, KK>(_source, _comparisons, keySelector, comparer, descending);
2867
public IEnumerator<T> GetEnumerator()
2870
// We sort using List<T>.Sort, but docs say that it performs an
2871
// unstable sort. LINQ, on the other hand, says OrderBy performs
2872
// a stable sort. So convert the source sequence into a sequence
2873
// of tuples where the second element tags the position of the
2874
// element from the source sequence (First). The position is
2875
// then used as a tie breaker when all keys compare equal,
2876
// thus making the sort stable.
2879
var list = _source.Select(new Func<T, int, Tuple<T, int>>(TagPosition)).ToList();
2884
// Compare keys from left to right.
2887
var comparisons = _comparisons;
2888
for (var i = 0; i < comparisons.Count; i++)
2890
var result = comparisons[i](x.First, y.First);
2896
// All keys compared equal so now break the tie by their
2897
// position in the original sequence, making the sort stable.
2900
return x.Second.CompareTo(y.Second);
2903
return list.Select(new Func<Tuple<T, int>, T>(GetFirst)).GetEnumerator();
2908
/// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a>
2909
/// for why this method is needed and cannot be expressed as a
2910
/// lambda at the call site.
2913
private static Tuple<T, int> TagPosition(T e, int i)
2915
return new Tuple<T, int>(e, i);
2919
/// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a>
2920
/// for why this method is needed and cannot be expressed as a
2921
/// lambda at the call site.
2924
private static T GetFirst(Tuple<T, int> pv)
2929
IEnumerator IEnumerable.GetEnumerator()
2931
return GetEnumerator();
2936
internal struct Tuple<TFirst, TSecond> : IEquatable<Tuple<TFirst, TSecond>>
2938
public TFirst First { get; private set; }
2939
public TSecond Second { get; private set; }
2941
public Tuple(TFirst first, TSecond second)
2948
public override bool Equals(object obj)
2951
&& obj is Tuple<TFirst, TSecond>
2952
&& base.Equals((Tuple<TFirst, TSecond>) obj);
2955
public bool Equals(Tuple<TFirst, TSecond> other)
2957
return EqualityComparer<TFirst>.Default.Equals(other.First, First)
2958
&& EqualityComparer<TSecond>.Default.Equals(other.Second, Second);
2961
public override int GetHashCode()
2963
var num = 0x7a2f0b42;
2964
num = (-1521134295*num) + EqualityComparer<TFirst>.Default.GetHashCode(First);
2965
return (-1521134295*num) + EqualityComparer<TSecond>.Default.GetHashCode(Second);
2968
public override string ToString()
2970
return string.Format(CultureInfo.InvariantCulture, @"{{ First = {0}, Second = {1} }}", First, Second);
2975
namespace Newtonsoft.Json.Serialization
2977
public delegate TResult Func<TResult>();
2979
public delegate TResult Func<T, TResult>(T a);
2981
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
2983
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
2985
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
2987
public delegate void Action();
2989
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
2991
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
2993
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
2996
namespace System.Runtime.CompilerServices
2999
/// This attribute allows us to define extension methods without
3000
/// requiring .NET Framework 3.5. For more information, see the section,
3001
/// <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7">Extension Methods in .NET Framework 2.0 Apps</a>,
3002
/// of <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx">Basic Instincts: Extension Methods</a>
3003
/// column in <a href="http://msdn.microsoft.com/msdnmag/">MSDN Magazine</a>,
3004
/// issue <a href="http://msdn.microsoft.com/en-us/magazine/cc135410.aspx">Nov 2007</a>.
3007
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
3008
internal sealed class ExtensionAttribute : Attribute { }
b'\\ No newline at end of file'