~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json/Utilities/LinqBridge.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
ļ»æ#if NET20
 
2
 
 
3
#region License, Terms and Author(s)
 
4
//
 
5
// LINQBridge
 
6
// Copyright (c) 2007-9 Atif Aziz, Joseph Albahari. All rights reserved.
 
7
//
 
8
//  Author(s):
 
9
//
 
10
//      Atif Aziz, http://www.raboof.com
 
11
//
 
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.
 
15
//
 
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.
 
27
//
 
28
#endregion
 
29
 
 
30
using System;
 
31
using System.Collections;
 
32
using System.Collections.Generic;
 
33
using System.Diagnostics;
 
34
using System.Globalization;
 
35
using Newtonsoft.Json.Serialization;
 
36
 
 
37
namespace Newtonsoft.Json.Utilities.LinqBridge
 
38
{
 
39
  /// <summary>
 
40
  /// Provides a set of static (Shared in Visual Basic) methods for 
 
41
  /// querying objects that implement <see cref="IEnumerable{T}" />.
 
42
  /// </summary>
 
43
  internal static partial class Enumerable
 
44
  {
 
45
    /// <summary>
 
46
    /// Returns the input typed as <see cref="IEnumerable{T}"/>.
 
47
    /// </summary>
 
48
 
 
49
    public static IEnumerable<TSource> AsEnumerable<TSource>(IEnumerable<TSource> source)
 
50
    {
 
51
      return source;
 
52
    }
 
53
 
 
54
    /// <summary>
 
55
    /// Returns an empty <see cref="IEnumerable{T}"/> that has the 
 
56
    /// specified type argument.
 
57
    /// </summary>
 
58
 
 
59
    public static IEnumerable<TResult> Empty<TResult>()
 
60
    {
 
61
      return Sequence<TResult>.Empty;
 
62
    }
 
63
 
 
64
    /// <summary>
 
65
    /// Converts the elements of an <see cref="IEnumerable"/> to the 
 
66
    /// specified type.
 
67
    /// </summary>
 
68
 
 
69
    public static IEnumerable<TResult> Cast<TResult>(
 
70
      this IEnumerable source)
 
71
    {
 
72
      CheckNotNull(source, "source");
 
73
 
 
74
      return CastYield<TResult>(source);
 
75
    }
 
76
 
 
77
    private static IEnumerable<TResult> CastYield<TResult>(
 
78
      IEnumerable source)
 
79
    {
 
80
      foreach (var item in source)
 
81
        yield return (TResult) item;
 
82
    }
 
83
 
 
84
    /// <summary>
 
85
    /// Filters the elements of an <see cref="IEnumerable"/> based on a specified type.
 
86
    /// </summary>
 
87
 
 
88
    public static IEnumerable<TResult> OfType<TResult>(
 
89
      this IEnumerable source)
 
90
    {
 
91
      CheckNotNull(source, "source");
 
92
 
 
93
      return OfTypeYield<TResult>(source);
 
94
    }
 
95
 
 
96
    private static IEnumerable<TResult> OfTypeYield<TResult>(
 
97
      IEnumerable source)
 
98
    {
 
99
      foreach (var item in source)
 
100
        if (item is TResult)
 
101
          yield return (TResult) item;
 
102
    }
 
103
 
 
104
    /// <summary>
 
105
    /// Generates a sequence of integral numbers within a specified range.
 
106
    /// </summary>
 
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>
 
109
 
 
110
    public static IEnumerable<int> Range(int start, int count)
 
111
    {
 
112
      if (count < 0)
 
113
        throw new ArgumentOutOfRangeException("count", count, null);
 
114
 
 
115
      var end = (long) start + count;
 
116
      if (end - 1 >= int.MaxValue)
 
117
        throw new ArgumentOutOfRangeException("count", count, null);
 
118
 
 
119
      return RangeYield(start, end);
 
120
    }
 
121
 
 
122
    private static IEnumerable<int> RangeYield(int start, long end)
 
123
    {
 
124
      for (var i = start; i < end; i++)
 
125
        yield return i;
 
126
    }
 
127
 
 
128
    /// <summary>
 
129
    /// Generates a sequence that contains one repeated value.
 
130
    /// </summary>
 
131
 
 
132
    public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
 
133
    {
 
134
      if (count < 0) throw new ArgumentOutOfRangeException("count", count, null);
 
135
 
 
136
      return RepeatYield(element, count);
 
137
    }
 
138
 
 
139
    private static IEnumerable<TResult> RepeatYield<TResult>(TResult element, int count)
 
140
    {
 
141
      for (var i = 0; i < count; i++)
 
142
        yield return element;
 
143
    }
 
144
 
 
145
    /// <summary>
 
146
    /// Filters a sequence of values based on a predicate.
 
147
    /// </summary>
 
148
 
 
149
    public static IEnumerable<TSource> Where<TSource>(
 
150
      this IEnumerable<TSource> source,
 
151
      Func<TSource, bool> predicate)
 
152
    {
 
153
      CheckNotNull(predicate, "predicate");
 
154
 
 
155
      return source.Where((item, i) => predicate(item));
 
156
    }
 
157
 
 
158
    /// <summary>
 
159
    /// Filters a sequence of values based on a predicate. 
 
160
    /// Each element's index is used in the logic of the predicate function.
 
161
    /// </summary>
 
162
 
 
163
    public static IEnumerable<TSource> Where<TSource>(
 
164
      this IEnumerable<TSource> source,
 
165
      Func<TSource, int, bool> predicate)
 
166
    {
 
167
      CheckNotNull(source, "source");
 
168
      CheckNotNull(predicate, "predicate");
 
169
 
 
170
      return WhereYield(source, predicate);
 
171
    }
 
172
 
 
173
    private static IEnumerable<TSource> WhereYield<TSource>(
 
174
      IEnumerable<TSource> source,
 
175
      Func<TSource, int, bool> predicate)
 
176
    {
 
177
      var i = 0;
 
178
      foreach (var item in source)
 
179
        if (predicate(item, i++))
 
180
          yield return item;
 
181
    }
 
182
 
 
183
    /// <summary>
 
184
    /// Projects each element of a sequence into a new form.
 
185
    /// </summary>
 
186
 
 
187
    public static IEnumerable<TResult> Select<TSource, TResult>(
 
188
      this IEnumerable<TSource> source,
 
189
      Func<TSource, TResult> selector)
 
190
    {
 
191
      CheckNotNull(selector, "selector");
 
192
 
 
193
      return source.Select((item, i) => selector(item));
 
194
    }
 
195
 
 
196
    /// <summary>
 
197
    /// Projects each element of a sequence into a new form by 
 
198
    /// incorporating the element's index.
 
199
    /// </summary>
 
200
 
 
201
    public static IEnumerable<TResult> Select<TSource, TResult>(
 
202
      this IEnumerable<TSource> source,
 
203
      Func<TSource, int, TResult> selector)
 
204
    {
 
205
      CheckNotNull(source, "source");
 
206
      CheckNotNull(selector, "selector");
 
207
 
 
208
      return SelectYield(source, selector);
 
209
    }
 
210
 
 
211
    private static IEnumerable<TResult> SelectYield<TSource, TResult>(
 
212
      IEnumerable<TSource> source,
 
213
      Func<TSource, int, TResult> selector)
 
214
    {
 
215
      var i = 0;
 
216
      foreach (var item in source)
 
217
        yield return selector(item, i++);
 
218
    }
 
219
 
 
220
    /// <summary>
 
221
    /// Projects each element of a sequence to an <see cref="IEnumerable{T}" /> 
 
222
    /// and flattens the resulting sequences into one sequence.
 
223
    /// </summary>
 
224
 
 
225
    public static IEnumerable<TResult> SelectMany<TSource, TResult>(
 
226
      this IEnumerable<TSource> source,
 
227
      Func<TSource, IEnumerable<TResult>> selector)
 
228
    {
 
229
      CheckNotNull(selector, "selector");
 
230
 
 
231
      return source.SelectMany((item, i) => selector(item));
 
232
    }
 
233
 
 
234
    /// <summary>
 
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 
 
238
    /// that element.
 
239
    /// </summary>
 
240
 
 
241
    public static IEnumerable<TResult> SelectMany<TSource, TResult>(
 
242
      this IEnumerable<TSource> source,
 
243
      Func<TSource, int, IEnumerable<TResult>> selector)
 
244
    {
 
245
      CheckNotNull(selector, "selector");
 
246
 
 
247
      return source.SelectMany(selector, (item, subitem) => subitem);
 
248
    }
 
249
 
 
250
    /// <summary>
 
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.
 
254
    /// </summary>
 
255
 
 
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)
 
260
    {
 
261
      CheckNotNull(collectionSelector, "collectionSelector");
 
262
 
 
263
      return source.SelectMany((item, i) => collectionSelector(item), resultSelector);
 
264
    }
 
265
 
 
266
    /// <summary>
 
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 
 
271
    /// of that element.
 
272
    /// </summary>
 
273
 
 
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)
 
278
    {
 
279
      CheckNotNull(source, "source");
 
280
      CheckNotNull(collectionSelector, "collectionSelector");
 
281
      CheckNotNull(resultSelector, "resultSelector");
 
282
 
 
283
      return SelectManyYield(source, collectionSelector, resultSelector);
 
284
    }
 
285
 
 
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)
 
290
    {
 
291
      var i = 0;
 
292
      foreach (var item in source)
 
293
        foreach (var subitem in collectionSelector(item, i++))
 
294
          yield return resultSelector(item, subitem);
 
295
    }
 
296
 
 
297
    /// <summary>
 
298
    /// Returns elements from a sequence as long as a specified condition is true.
 
299
    /// </summary>
 
300
 
 
301
    public static IEnumerable<TSource> TakeWhile<TSource>(
 
302
      this IEnumerable<TSource> source,
 
303
      Func<TSource, bool> predicate)
 
304
    {
 
305
      CheckNotNull(predicate, "predicate");
 
306
 
 
307
      return source.TakeWhile((item, i) => predicate(item));
 
308
    }
 
309
 
 
310
    /// <summary>
 
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.
 
313
    /// </summary>
 
314
 
 
315
    public static IEnumerable<TSource> TakeWhile<TSource>(
 
316
      this IEnumerable<TSource> source,
 
317
      Func<TSource, int, bool> predicate)
 
318
    {
 
319
      CheckNotNull(source, "source");
 
320
      CheckNotNull(predicate, "predicate");
 
321
 
 
322
      return TakeWhileYield(source, predicate);
 
323
    }
 
324
 
 
325
    private static IEnumerable<TSource> TakeWhileYield<TSource>(
 
326
      this IEnumerable<TSource> source,
 
327
      Func<TSource, int, bool> predicate)
 
328
    {
 
329
      var i = 0;
 
330
      foreach (var item in source)
 
331
        if (predicate(item, i++))
 
332
          yield return item;
 
333
        else
 
334
          break;
 
335
    }
 
336
 
 
337
    private static class Futures<T>
 
338
    {
 
339
      public static readonly Func<T> Default = () => default(T);
 
340
      public static readonly Func<T> Undefined = () => { throw new InvalidOperationException(); };
 
341
    }
 
342
 
 
343
    /// <summary>
 
344
    /// Base implementation of First operator.
 
345
    /// </summary>
 
346
 
 
347
    private static TSource FirstImpl<TSource>(
 
348
      this IEnumerable<TSource> source,
 
349
      Func<TSource> empty)
 
350
    {
 
351
      CheckNotNull(source, "source");
 
352
      Debug.Assert(empty != null);
 
353
 
 
354
      var list = source as IList<TSource>; // optimized case for lists
 
355
      if (list != null)
 
356
        return list.Count > 0 ? list[0] : empty();
 
357
 
 
358
      using (var e = source.GetEnumerator()) // fallback for enumeration
 
359
        return e.MoveNext() ? e.Current : empty();
 
360
    }
 
361
 
 
362
    /// <summary>
 
363
    /// Returns the first element of a sequence.
 
364
    /// </summary>
 
365
 
 
366
    public static TSource First<TSource>(
 
367
      this IEnumerable<TSource> source)
 
368
    {
 
369
      return source.FirstImpl(Futures<TSource>.Undefined);
 
370
    }
 
371
 
 
372
    /// <summary>
 
373
    /// Returns the first element in a sequence that satisfies a specified condition.
 
374
    /// </summary>
 
375
 
 
376
    public static TSource First<TSource>(
 
377
      this IEnumerable<TSource> source,
 
378
      Func<TSource, bool> predicate)
 
379
    {
 
380
      return First(source.Where(predicate));
 
381
    }
 
382
 
 
383
    /// <summary>
 
384
    /// Returns the first element of a sequence, or a default value if 
 
385
    /// the sequence contains no elements.
 
386
    /// </summary>
 
387
 
 
388
    public static TSource FirstOrDefault<TSource>(
 
389
      this IEnumerable<TSource> source)
 
390
    {
 
391
      return source.FirstImpl(Futures<TSource>.Default);
 
392
    }
 
393
 
 
394
    /// <summary>
 
395
    /// Returns the first element of the sequence that satisfies a 
 
396
    /// condition or a default value if no such element is found.
 
397
    /// </summary>
 
398
 
 
399
    public static TSource FirstOrDefault<TSource>(
 
400
      this IEnumerable<TSource> source,
 
401
      Func<TSource, bool> predicate)
 
402
    {
 
403
      return FirstOrDefault(source.Where(predicate));
 
404
    }
 
405
 
 
406
    /// <summary>
 
407
    /// Base implementation of Last operator.
 
408
    /// </summary>
 
409
 
 
410
    private static TSource LastImpl<TSource>(
 
411
      this IEnumerable<TSource> source,
 
412
      Func<TSource> empty)
 
413
    {
 
414
      CheckNotNull(source, "source");
 
415
 
 
416
      var list = source as IList<TSource>; // optimized case for lists
 
417
      if (list != null)
 
418
        return list.Count > 0 ? list[list.Count - 1] : empty();
 
419
 
 
420
      using (var e = source.GetEnumerator())
 
421
      {
 
422
        if (!e.MoveNext())
 
423
          return empty();
 
424
 
 
425
        var last = e.Current;
 
426
        while (e.MoveNext())
 
427
          last = e.Current;
 
428
 
 
429
        return last;
 
430
      }
 
431
    }
 
432
 
 
433
    /// <summary>
 
434
    /// Returns the last element of a sequence.
 
435
    /// </summary>
 
436
    public static TSource Last<TSource>(
 
437
      this IEnumerable<TSource> source)
 
438
    {
 
439
      return source.LastImpl(Futures<TSource>.Undefined);
 
440
    }
 
441
 
 
442
    /// <summary>
 
443
    /// Returns the last element of a sequence that satisfies a 
 
444
    /// specified condition.
 
445
    /// </summary>
 
446
 
 
447
    public static TSource Last<TSource>(
 
448
      this IEnumerable<TSource> source,
 
449
      Func<TSource, bool> predicate)
 
450
    {
 
451
      return Last(source.Where(predicate));
 
452
    }
 
453
 
 
454
    /// <summary>
 
455
    /// Returns the last element of a sequence, or a default value if 
 
456
    /// the sequence contains no elements.
 
457
    /// </summary>
 
458
 
 
459
    public static TSource LastOrDefault<TSource>(
 
460
      this IEnumerable<TSource> source)
 
461
    {
 
462
      return source.LastImpl(Futures<TSource>.Default);
 
463
    }
 
464
 
 
465
    /// <summary>
 
466
    /// Returns the last element of a sequence that satisfies a 
 
467
    /// condition or a default value if no such element is found.
 
468
    /// </summary>
 
469
 
 
470
    public static TSource LastOrDefault<TSource>(
 
471
      this IEnumerable<TSource> source,
 
472
      Func<TSource, bool> predicate)
 
473
    {
 
474
      return LastOrDefault(source.Where(predicate));
 
475
    }
 
476
 
 
477
    /// <summary>
 
478
    /// Base implementation of Single operator.
 
479
    /// </summary>
 
480
 
 
481
    private static TSource SingleImpl<TSource>(
 
482
      this IEnumerable<TSource> source,
 
483
      Func<TSource> empty)
 
484
    {
 
485
      CheckNotNull(source, "source");
 
486
 
 
487
      using (var e = source.GetEnumerator())
 
488
      {
 
489
        if (e.MoveNext())
 
490
        {
 
491
          var single = e.Current;
 
492
          if (!e.MoveNext())
 
493
            return single;
 
494
 
 
495
          throw new InvalidOperationException();
 
496
        }
 
497
 
 
498
        return empty();
 
499
      }
 
500
    }
 
501
 
 
502
    /// <summary>
 
503
    /// Returns the only element of a sequence, and throws an exception 
 
504
    /// if there is not exactly one element in the sequence.
 
505
    /// </summary>
 
506
 
 
507
    public static TSource Single<TSource>(
 
508
      this IEnumerable<TSource> source)
 
509
    {
 
510
      return source.SingleImpl(Futures<TSource>.Undefined);
 
511
    }
 
512
 
 
513
    /// <summary>
 
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.
 
517
    /// </summary>
 
518
 
 
519
    public static TSource Single<TSource>(
 
520
      this IEnumerable<TSource> source,
 
521
      Func<TSource, bool> predicate)
 
522
    {
 
523
      return Single(source.Where(predicate));
 
524
    }
 
525
 
 
526
    /// <summary>
 
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.
 
530
    /// </summary>
 
531
 
 
532
    public static TSource SingleOrDefault<TSource>(
 
533
      this IEnumerable<TSource> source)
 
534
    {
 
535
      return source.SingleImpl(Futures<TSource>.Default);
 
536
    }
 
537
 
 
538
    /// <summary>
 
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.
 
543
    /// </summary>
 
544
 
 
545
    public static TSource SingleOrDefault<TSource>(
 
546
      this IEnumerable<TSource> source,
 
547
      Func<TSource, bool> predicate)
 
548
    {
 
549
      return SingleOrDefault(source.Where(predicate));
 
550
    }
 
551
 
 
552
    /// <summary>
 
553
    /// Returns the element at a specified index in a sequence.
 
554
    /// </summary>
 
555
 
 
556
    public static TSource ElementAt<TSource>(
 
557
      this IEnumerable<TSource> source,
 
558
      int index)
 
559
    {
 
560
      CheckNotNull(source, "source");
 
561
 
 
562
      if (index < 0)
 
563
        throw new ArgumentOutOfRangeException("index", index, null);
 
564
 
 
565
      var list = source as IList<TSource>;
 
566
      if (list != null)
 
567
        return list[index];
 
568
 
 
569
      try
 
570
      {
 
571
        return source.SkipWhile((item, i) => i < index).First();
 
572
      }
 
573
      catch (InvalidOperationException) // if thrown by First
 
574
      {
 
575
        throw new ArgumentOutOfRangeException("index", index, null);
 
576
      }
 
577
    }
 
578
 
 
579
    /// <summary>
 
580
    /// Returns the element at a specified index in a sequence or a 
 
581
    /// default value if the index is out of range.
 
582
    /// </summary>
 
583
 
 
584
    public static TSource ElementAtOrDefault<TSource>(
 
585
      this IEnumerable<TSource> source,
 
586
      int index)
 
587
    {
 
588
      CheckNotNull(source, "source");
 
589
 
 
590
      if (index < 0)
 
591
        return default(TSource);
 
592
 
 
593
      var list = source as IList<TSource>;
 
594
      if (list != null)
 
595
        return index < list.Count ? list[index] : default(TSource);
 
596
 
 
597
      return source.SkipWhile((item, i) => i < index).FirstOrDefault();
 
598
    }
 
599
 
 
600
    /// <summary>
 
601
    /// Inverts the order of the elements in a sequence.
 
602
    /// </summary>
 
603
 
 
604
    public static IEnumerable<TSource> Reverse<TSource>(
 
605
      this IEnumerable<TSource> source)
 
606
    {
 
607
      CheckNotNull(source, "source");
 
608
 
 
609
      return ReverseYield(source);
 
610
    }
 
611
 
 
612
    private static IEnumerable<TSource> ReverseYield<TSource>(IEnumerable<TSource> source)
 
613
    {
 
614
      var stack = new Stack<TSource>();
 
615
      foreach (var item in source)
 
616
        stack.Push(item);
 
617
 
 
618
      foreach (var item in stack)
 
619
        yield return item;
 
620
    }
 
621
 
 
622
    /// <summary>
 
623
    /// Returns a specified number of contiguous elements from the start 
 
624
    /// of a sequence.
 
625
    /// </summary>
 
626
 
 
627
    public static IEnumerable<TSource> Take<TSource>(
 
628
      this IEnumerable<TSource> source,
 
629
      int count)
 
630
    {
 
631
      return source.Where((item, i) => i < count);
 
632
    }
 
633
 
 
634
    /// <summary>
 
635
    /// Bypasses a specified number of elements in a sequence and then 
 
636
    /// returns the remaining elements.
 
637
    /// </summary>
 
638
 
 
639
    public static IEnumerable<TSource> Skip<TSource>(
 
640
      this IEnumerable<TSource> source,
 
641
      int count)
 
642
    {
 
643
      return source.Where((item, i) => i >= count);
 
644
    }
 
645
 
 
646
    /// <summary>
 
647
    /// Bypasses elements in a sequence as long as a specified condition 
 
648
    /// is true and then returns the remaining elements.
 
649
    /// </summary>
 
650
 
 
651
    public static IEnumerable<TSource> SkipWhile<TSource>(
 
652
      this IEnumerable<TSource> source,
 
653
      Func<TSource, bool> predicate)
 
654
    {
 
655
      CheckNotNull(predicate, "predicate");
 
656
 
 
657
      return source.SkipWhile((item, i) => predicate(item));
 
658
    }
 
659
 
 
660
    /// <summary>
 
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.
 
664
    /// </summary>
 
665
 
 
666
    public static IEnumerable<TSource> SkipWhile<TSource>(
 
667
      this IEnumerable<TSource> source,
 
668
      Func<TSource, int, bool> predicate)
 
669
    {
 
670
      CheckNotNull(source, "source");
 
671
      CheckNotNull(predicate, "predicate");
 
672
 
 
673
      return SkipWhileYield(source, predicate);
 
674
    }
 
675
 
 
676
    private static IEnumerable<TSource> SkipWhileYield<TSource>(
 
677
      IEnumerable<TSource> source,
 
678
      Func<TSource, int, bool> predicate)
 
679
    {
 
680
      using (var e = source.GetEnumerator())
 
681
      {
 
682
        for (var i = 0;; i++)
 
683
        {
 
684
          if (!e.MoveNext())
 
685
            yield break;
 
686
 
 
687
          if (!predicate(e.Current, i))
 
688
            break;
 
689
        }
 
690
 
 
691
        do
 
692
        {
 
693
          yield return e.Current;
 
694
        } while (e.MoveNext());
 
695
      }
 
696
    }
 
697
 
 
698
    /// <summary>
 
699
    /// Returns the number of elements in a sequence.
 
700
    /// </summary>
 
701
 
 
702
    public static int Count<TSource>(
 
703
      this IEnumerable<TSource> source)
 
704
    {
 
705
      CheckNotNull(source, "source");
 
706
 
 
707
      var collection = source as ICollection;
 
708
      return collection != null
 
709
               ? collection.Count
 
710
               : source.Aggregate(0, (count, item) => checked(count + 1));
 
711
    }
 
712
 
 
713
    /// <summary>
 
714
    /// Returns a number that represents how many elements in the 
 
715
    /// specified sequence satisfy a condition.
 
716
    /// </summary>
 
717
 
 
718
    public static int Count<TSource>(
 
719
      this IEnumerable<TSource> source,
 
720
      Func<TSource, bool> predicate)
 
721
    {
 
722
      return Count(source.Where(predicate));
 
723
    }
 
724
 
 
725
    /// <summary>
 
726
    /// Returns an <see cref="Int64"/> that represents the total number 
 
727
    /// of elements in a sequence.
 
728
    /// </summary>
 
729
 
 
730
    public static long LongCount<TSource>(
 
731
      this IEnumerable<TSource> source)
 
732
    {
 
733
      CheckNotNull(source, "source");
 
734
 
 
735
      var array = source as Array;
 
736
      return array != null
 
737
               ? array.LongLength
 
738
               : source.Aggregate(0L, (count, item) => count + 1);
 
739
    }
 
740
 
 
741
    /// <summary>
 
742
    /// Returns an <see cref="Int64"/> that represents how many elements 
 
743
    /// in a sequence satisfy a condition.
 
744
    /// </summary>
 
745
 
 
746
    public static long LongCount<TSource>(
 
747
      this IEnumerable<TSource> source,
 
748
      Func<TSource, bool> predicate)
 
749
    {
 
750
      return LongCount(source.Where(predicate));
 
751
    }
 
752
 
 
753
    /// <summary>
 
754
    /// Concatenates two sequences.
 
755
    /// </summary>
 
756
 
 
757
    public static IEnumerable<TSource> Concat<TSource>(
 
758
      this IEnumerable<TSource> first,
 
759
      IEnumerable<TSource> second)
 
760
    {
 
761
      CheckNotNull(first, "first");
 
762
      CheckNotNull(second, "second");
 
763
 
 
764
      return ConcatYield(first, second);
 
765
    }
 
766
 
 
767
    private static IEnumerable<TSource> ConcatYield<TSource>(
 
768
      IEnumerable<TSource> first,
 
769
      IEnumerable<TSource> second)
 
770
    {
 
771
      foreach (var item in first)
 
772
        yield return item;
 
773
 
 
774
      foreach (var item in second)
 
775
        yield return item;
 
776
    }
 
777
 
 
778
    /// <summary>
 
779
    /// Creates a <see cref="List{T}"/> from an <see cref="IEnumerable{T}"/>.
 
780
    /// </summary>
 
781
 
 
782
    public static List<TSource> ToList<TSource>(
 
783
      this IEnumerable<TSource> source)
 
784
    {
 
785
      CheckNotNull(source, "source");
 
786
 
 
787
      return new List<TSource>(source);
 
788
    }
 
789
 
 
790
    /// <summary>
 
791
    /// Creates an array from an <see cref="IEnumerable{T}"/>.
 
792
    /// </summary>
 
793
 
 
794
    public static TSource[] ToArray<TSource>(
 
795
      this IEnumerable<TSource> source)
 
796
    {
 
797
      return source.ToList().ToArray();
 
798
    }
 
799
 
 
800
    /// <summary>
 
801
    /// Returns distinct elements from a sequence by using the default 
 
802
    /// equality comparer to compare values.
 
803
    /// </summary>
 
804
 
 
805
    public static IEnumerable<TSource> Distinct<TSource>(
 
806
      this IEnumerable<TSource> source)
 
807
    {
 
808
      return Distinct(source, /* comparer */ null);
 
809
    }
 
810
 
 
811
    /// <summary>
 
812
    /// Returns distinct elements from a sequence by using a specified 
 
813
    /// <see cref="IEqualityComparer{T}"/> to compare values.
 
814
    /// </summary>
 
815
 
 
816
    public static IEnumerable<TSource> Distinct<TSource>(
 
817
      this IEnumerable<TSource> source,
 
818
      IEqualityComparer<TSource> comparer)
 
819
    {
 
820
      CheckNotNull(source, "source");
 
821
 
 
822
      return DistinctYield(source, comparer);
 
823
    }
 
824
 
 
825
    private static IEnumerable<TSource> DistinctYield<TSource>(
 
826
      IEnumerable<TSource> source,
 
827
      IEqualityComparer<TSource> comparer)
 
828
    {
 
829
      var set = new Dictionary<TSource, object>(comparer);
 
830
      var gotNull = false;
 
831
 
 
832
      foreach (var item in source)
 
833
      {
 
834
        if (item == null)
 
835
        {
 
836
          if (gotNull)
 
837
            continue;
 
838
          gotNull = true;
 
839
        }
 
840
        else
 
841
        {
 
842
          if (set.ContainsKey(item))
 
843
            continue;
 
844
          set.Add(item, null);
 
845
        }
 
846
 
 
847
        yield return item;
 
848
      }
 
849
    }
 
850
 
 
851
    /// <summary>
 
852
    /// Creates a <see cref="Lookup{TKey,TElement}" /> from an 
 
853
    /// <see cref="IEnumerable{T}" /> according to a specified key 
 
854
    /// selector function.
 
855
    /// </summary>
 
856
 
 
857
    public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
 
858
      this IEnumerable<TSource> source,
 
859
      Func<TSource, TKey> keySelector)
 
860
    {
 
861
      return ToLookup(source, keySelector, e => e, /* comparer */ null);
 
862
    }
 
863
 
 
864
    /// <summary>
 
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.
 
868
    /// </summary>
 
869
 
 
870
    public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
 
871
      this IEnumerable<TSource> source,
 
872
      Func<TSource, TKey> keySelector,
 
873
      IEqualityComparer<TKey> comparer)
 
874
    {
 
875
      return ToLookup(source, keySelector, e => e, comparer);
 
876
    }
 
877
 
 
878
    /// <summary>
 
879
    /// Creates a <see cref="Lookup{TKey,TElement}" /> from an 
 
880
    /// <see cref="IEnumerable{T}" /> according to specified key 
 
881
    /// and element selector functions.
 
882
    /// </summary>
 
883
 
 
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)
 
888
    {
 
889
      return ToLookup(source, keySelector, elementSelector, /* comparer */ null);
 
890
    }
 
891
 
 
892
    /// <summary>
 
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.
 
896
    /// </summary>
 
897
 
 
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)
 
903
    {
 
904
      CheckNotNull(source, "source");
 
905
      CheckNotNull(keySelector, "keySelector");
 
906
      CheckNotNull(elementSelector, "elementSelector");
 
907
 
 
908
      var lookup = new Lookup<TKey, TElement>(comparer);
 
909
 
 
910
      foreach (var item in source)
 
911
      {
 
912
        var key = keySelector(item);
 
913
 
 
914
        var grouping = (Grouping<TKey, TElement>) lookup.Find(key);
 
915
        if (grouping == null)
 
916
        {
 
917
          grouping = new Grouping<TKey, TElement>(key);
 
918
          lookup.Add(grouping);
 
919
        }
 
920
 
 
921
        grouping.Add(elementSelector(item));
 
922
      }
 
923
 
 
924
      return lookup;
 
925
    }
 
926
 
 
927
    /// <summary>
 
928
    /// Groups the elements of a sequence according to a specified key 
 
929
    /// selector function.
 
930
    /// </summary>
 
931
 
 
932
    public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
 
933
      this IEnumerable<TSource> source,
 
934
      Func<TSource, TKey> keySelector)
 
935
    {
 
936
      return GroupBy(source, keySelector, /* comparer */ null);
 
937
    }
 
938
 
 
939
    /// <summary>
 
940
    /// Groups the elements of a sequence according to a specified key 
 
941
    /// selector function and compares the keys by using a specified 
 
942
    /// comparer.
 
943
    /// </summary>
 
944
 
 
945
    public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
 
946
      this IEnumerable<TSource> source,
 
947
      Func<TSource, TKey> keySelector,
 
948
      IEqualityComparer<TKey> comparer)
 
949
    {
 
950
      return GroupBy(source, keySelector, e => e, comparer);
 
951
    }
 
952
 
 
953
    /// <summary>
 
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.
 
957
    /// </summary>
 
958
 
 
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)
 
963
    {
 
964
      return GroupBy(source, keySelector, elementSelector, /* comparer */ null);
 
965
    }
 
966
 
 
967
    /// <summary>
 
968
    /// Groups the elements of a sequence according to a specified key 
 
969
    /// selector function and creates a result value from each group and 
 
970
    /// its key.
 
971
    /// </summary>
 
972
 
 
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)
 
978
    {
 
979
      CheckNotNull(source, "source");
 
980
      CheckNotNull(keySelector, "keySelector");
 
981
      CheckNotNull(elementSelector, "elementSelector");
 
982
 
 
983
      return ToLookup(source, keySelector, elementSelector, comparer);
 
984
    }
 
985
 
 
986
    /// <summary>
 
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.
 
990
    /// </summary>
 
991
 
 
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)
 
996
    {
 
997
      return GroupBy(source, keySelector, resultSelector, /* comparer */ null);
 
998
    }
 
999
 
 
1000
    /// <summary>
 
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.
 
1005
    /// </summary>
 
1006
 
 
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)
 
1012
    {
 
1013
      CheckNotNull(source, "source");
 
1014
      CheckNotNull(keySelector, "keySelector");
 
1015
      CheckNotNull(resultSelector, "resultSelector");
 
1016
 
 
1017
      return ToLookup(source, keySelector, comparer).Select(g => resultSelector(g.Key, g));
 
1018
    }
 
1019
 
 
1020
    /// <summary>
 
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.
 
1024
    /// </summary>
 
1025
 
 
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)
 
1031
    {
 
1032
      return GroupBy(source, keySelector, elementSelector, resultSelector, /* comparer */ null);
 
1033
    }
 
1034
 
 
1035
    /// <summary>
 
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.
 
1041
    /// </summary>
 
1042
 
 
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)
 
1049
    {
 
1050
      CheckNotNull(source, "source");
 
1051
      CheckNotNull(keySelector, "keySelector");
 
1052
      CheckNotNull(elementSelector, "elementSelector");
 
1053
      CheckNotNull(resultSelector, "resultSelector");
 
1054
 
 
1055
      return ToLookup(source, keySelector, elementSelector, comparer)
 
1056
        .Select(g => resultSelector(g.Key, g));
 
1057
    }
 
1058
 
 
1059
    /// <summary>
 
1060
    /// Applies an accumulator function over a sequence.
 
1061
    /// </summary>
 
1062
 
 
1063
    public static TSource Aggregate<TSource>(
 
1064
      this IEnumerable<TSource> source,
 
1065
      Func<TSource, TSource, TSource> func)
 
1066
    {
 
1067
      CheckNotNull(source, "source");
 
1068
      CheckNotNull(func, "func");
 
1069
 
 
1070
      using (var e = source.GetEnumerator())
 
1071
      {
 
1072
        if (!e.MoveNext())
 
1073
          throw new InvalidOperationException();
 
1074
 
 
1075
        return e.Renumerable().Skip(1).Aggregate(e.Current, func);
 
1076
      }
 
1077
    }
 
1078
 
 
1079
    /// <summary>
 
1080
    /// Applies an accumulator function over a sequence. The specified 
 
1081
    /// seed value is used as the initial accumulator value.
 
1082
    /// </summary>
 
1083
 
 
1084
    public static TAccumulate Aggregate<TSource, TAccumulate>(
 
1085
      this IEnumerable<TSource> source,
 
1086
      TAccumulate seed,
 
1087
      Func<TAccumulate, TSource, TAccumulate> func)
 
1088
    {
 
1089
      return Aggregate(source, seed, func, r => r);
 
1090
    }
 
1091
 
 
1092
    /// <summary>
 
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.
 
1096
    /// </summary>
 
1097
 
 
1098
    public static TResult Aggregate<TSource, TAccumulate, TResult>(
 
1099
      this IEnumerable<TSource> source,
 
1100
      TAccumulate seed,
 
1101
      Func<TAccumulate, TSource, TAccumulate> func,
 
1102
      Func<TAccumulate, TResult> resultSelector)
 
1103
    {
 
1104
      CheckNotNull(source, "source");
 
1105
      CheckNotNull(func, "func");
 
1106
      CheckNotNull(resultSelector, "resultSelector");
 
1107
 
 
1108
      var result = seed;
 
1109
 
 
1110
      foreach (var item in source)
 
1111
        result = func(result, item);
 
1112
 
 
1113
      return resultSelector(result);
 
1114
    }
 
1115
 
 
1116
    /// <summary>
 
1117
    /// Produces the set union of two sequences by using the default 
 
1118
    /// equality comparer.
 
1119
    /// </summary>
 
1120
 
 
1121
    public static IEnumerable<TSource> Union<TSource>(
 
1122
      this IEnumerable<TSource> first,
 
1123
      IEnumerable<TSource> second)
 
1124
    {
 
1125
      return Union(first, second, /* comparer */ null);
 
1126
    }
 
1127
 
 
1128
    /// <summary>
 
1129
    /// Produces the set union of two sequences by using a specified 
 
1130
    /// <see cref="IEqualityComparer{T}" />.
 
1131
    /// </summary>
 
1132
 
 
1133
    public static IEnumerable<TSource> Union<TSource>(
 
1134
      this IEnumerable<TSource> first,
 
1135
      IEnumerable<TSource> second,
 
1136
      IEqualityComparer<TSource> comparer)
 
1137
    {
 
1138
      return first.Concat(second).Distinct(comparer);
 
1139
    }
 
1140
 
 
1141
    /// <summary>
 
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.
 
1145
    /// </summary>
 
1146
 
 
1147
    public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
 
1148
      this IEnumerable<TSource> source)
 
1149
    {
 
1150
      return source.DefaultIfEmpty(default(TSource));
 
1151
    }
 
1152
 
 
1153
    /// <summary>
 
1154
    /// Returns the elements of the specified sequence or the specified 
 
1155
    /// value in a singleton collection if the sequence is empty.
 
1156
    /// </summary>
 
1157
 
 
1158
    public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
 
1159
      this IEnumerable<TSource> source,
 
1160
      TSource defaultValue)
 
1161
    {
 
1162
      CheckNotNull(source, "source");
 
1163
 
 
1164
      return DefaultIfEmptyYield(source, defaultValue);
 
1165
    }
 
1166
 
 
1167
    private static IEnumerable<TSource> DefaultIfEmptyYield<TSource>(
 
1168
      IEnumerable<TSource> source,
 
1169
      TSource defaultValue)
 
1170
    {
 
1171
      using (var e = source.GetEnumerator())
 
1172
      {
 
1173
        if (!e.MoveNext())
 
1174
          yield return defaultValue;
 
1175
        else
 
1176
          do
 
1177
          {
 
1178
            yield return e.Current;
 
1179
          } while (e.MoveNext());
 
1180
      }
 
1181
    }
 
1182
 
 
1183
    /// <summary>
 
1184
    /// Determines whether all elements of a sequence satisfy a condition.
 
1185
    /// </summary>
 
1186
 
 
1187
    public static bool All<TSource>(
 
1188
      this IEnumerable<TSource> source,
 
1189
      Func<TSource, bool> predicate)
 
1190
    {
 
1191
      CheckNotNull(source, "source");
 
1192
      CheckNotNull(predicate, "predicate");
 
1193
 
 
1194
      foreach (var item in source)
 
1195
        if (!predicate(item))
 
1196
          return false;
 
1197
 
 
1198
      return true;
 
1199
    }
 
1200
 
 
1201
    /// <summary>
 
1202
    /// Determines whether a sequence contains any elements.
 
1203
    /// </summary>
 
1204
 
 
1205
    public static bool Any<TSource>(
 
1206
      this IEnumerable<TSource> source)
 
1207
    {
 
1208
      CheckNotNull(source, "source");
 
1209
 
 
1210
      using (var e = source.GetEnumerator())
 
1211
        return e.MoveNext();
 
1212
    }
 
1213
 
 
1214
    /// <summary>
 
1215
    /// Determines whether any element of a sequence satisfies a 
 
1216
    /// condition.
 
1217
    /// </summary>
 
1218
 
 
1219
    public static bool Any<TSource>(
 
1220
      this IEnumerable<TSource> source,
 
1221
      Func<TSource, bool> predicate)
 
1222
    {
 
1223
      return source.Where(predicate).Any();
 
1224
    }
 
1225
 
 
1226
    /// <summary>
 
1227
    /// Determines whether a sequence contains a specified element by 
 
1228
    /// using the default equality comparer.
 
1229
    /// </summary>
 
1230
 
 
1231
    public static bool Contains<TSource>(
 
1232
      this IEnumerable<TSource> source,
 
1233
      TSource value)
 
1234
    {
 
1235
      return source.Contains(value, /* comparer */ null);
 
1236
    }
 
1237
 
 
1238
    /// <summary>
 
1239
    /// Determines whether a sequence contains a specified element by 
 
1240
    /// using a specified <see cref="IEqualityComparer{T}" />.
 
1241
    /// </summary>
 
1242
 
 
1243
    public static bool Contains<TSource>(
 
1244
      this IEnumerable<TSource> source,
 
1245
      TSource value,
 
1246
      IEqualityComparer<TSource> comparer)
 
1247
    {
 
1248
      CheckNotNull(source, "source");
 
1249
 
 
1250
      if (comparer == null)
 
1251
      {
 
1252
        var collection = source as ICollection<TSource>;
 
1253
        if (collection != null)
 
1254
          return collection.Contains(value);
 
1255
      }
 
1256
 
 
1257
      comparer = comparer ?? EqualityComparer<TSource>.Default;
 
1258
      return source.Any(item => comparer.Equals(item, value));
 
1259
    }
 
1260
 
 
1261
    /// <summary>
 
1262
    /// Determines whether two sequences are equal by comparing the 
 
1263
    /// elements by using the default equality comparer for their type.
 
1264
    /// </summary>
 
1265
 
 
1266
    public static bool SequenceEqual<TSource>(
 
1267
      this IEnumerable<TSource> first,
 
1268
      IEnumerable<TSource> second)
 
1269
    {
 
1270
      return first.SequenceEqual(second, /* comparer */ null);
 
1271
    }
 
1272
 
 
1273
    /// <summary>
 
1274
    /// Determines whether two sequences are equal by comparing their 
 
1275
    /// elements by using a specified <see cref="IEqualityComparer{T}" />.
 
1276
    /// </summary>
 
1277
 
 
1278
    public static bool SequenceEqual<TSource>(
 
1279
      this IEnumerable<TSource> first,
 
1280
      IEnumerable<TSource> second,
 
1281
      IEqualityComparer<TSource> comparer)
 
1282
    {
 
1283
      CheckNotNull(first, "frist");
 
1284
      CheckNotNull(second, "second");
 
1285
 
 
1286
      comparer = comparer ?? EqualityComparer<TSource>.Default;
 
1287
 
 
1288
      using (IEnumerator<TSource> lhs = first.GetEnumerator(),
 
1289
                                  rhs = second.GetEnumerator())
 
1290
      {
 
1291
        do
 
1292
        {
 
1293
          if (!lhs.MoveNext())
 
1294
            return !rhs.MoveNext();
 
1295
 
 
1296
          if (!rhs.MoveNext())
 
1297
            return false;
 
1298
        } while (comparer.Equals(lhs.Current, rhs.Current));
 
1299
      }
 
1300
 
 
1301
      return false;
 
1302
    }
 
1303
 
 
1304
    /// <summary>
 
1305
    /// Base implementation for Min/Max operator.
 
1306
    /// </summary>
 
1307
 
 
1308
    private static TSource MinMaxImpl<TSource>(
 
1309
      this IEnumerable<TSource> source,
 
1310
      Func<TSource, TSource, bool> lesser)
 
1311
    {
 
1312
      CheckNotNull(source, "source");
 
1313
      Debug.Assert(lesser != null);
 
1314
 
 
1315
      return source.Aggregate((a, item) => lesser(a, item) ? a : item);
 
1316
    }
 
1317
 
 
1318
    /// <summary>
 
1319
    /// Base implementation for Min/Max operator for nullable types.
 
1320
    /// </summary>
 
1321
 
 
1322
    private static TSource? MinMaxImpl<TSource>(
 
1323
      this IEnumerable<TSource?> source,
 
1324
      TSource? seed, Func<TSource?, TSource?, bool> lesser) where TSource : struct
 
1325
    {
 
1326
      CheckNotNull(source, "source");
 
1327
      Debug.Assert(lesser != null);
 
1328
 
 
1329
      return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item);
 
1330
      //  == MinMaxImpl(Repeat<TSource?>(null, 1).Concat(source), lesser);
 
1331
    }
 
1332
 
 
1333
    /// <summary>
 
1334
    /// Returns the minimum value in a generic sequence.
 
1335
    /// </summary>
 
1336
 
 
1337
    public static TSource Min<TSource>(
 
1338
      this IEnumerable<TSource> source)
 
1339
    {
 
1340
      var comparer = Comparer<TSource>.Default;
 
1341
      return source.MinMaxImpl((x, y) => comparer.Compare(x, y) < 0);
 
1342
    }
 
1343
 
 
1344
    /// <summary>
 
1345
    /// Invokes a transform function on each element of a generic 
 
1346
    /// sequence and returns the minimum resulting value.
 
1347
    /// </summary>
 
1348
 
 
1349
    public static TResult Min<TSource, TResult>(
 
1350
      this IEnumerable<TSource> source,
 
1351
      Func<TSource, TResult> selector)
 
1352
    {
 
1353
      return source.Select(selector).Min();
 
1354
    }
 
1355
 
 
1356
    /// <summary>
 
1357
    /// Returns the maximum value in a generic sequence.
 
1358
    /// </summary>
 
1359
 
 
1360
    public static TSource Max<TSource>(
 
1361
      this IEnumerable<TSource> source)
 
1362
    {
 
1363
      var comparer = Comparer<TSource>.Default;
 
1364
      return source.MinMaxImpl((x, y) => comparer.Compare(x, y) > 0);
 
1365
    }
 
1366
 
 
1367
    /// <summary>
 
1368
    /// Invokes a transform function on each element of a generic 
 
1369
    /// sequence and returns the maximum resulting value.
 
1370
    /// </summary>
 
1371
 
 
1372
    public static TResult Max<TSource, TResult>(
 
1373
      this IEnumerable<TSource> source,
 
1374
      Func<TSource, TResult> selector)
 
1375
    {
 
1376
      return source.Select(selector).Max();
 
1377
    }
 
1378
 
 
1379
    /// <summary>
 
1380
    /// Makes an enumerator seen as enumerable once more.
 
1381
    /// </summary>
 
1382
    /// <remarks>
 
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.
 
1387
    /// </remarks>
 
1388
 
 
1389
    private static IEnumerable<T> Renumerable<T>(this IEnumerator<T> e)
 
1390
    {
 
1391
      Debug.Assert(e != null);
 
1392
 
 
1393
      do
 
1394
      {
 
1395
        yield return e.Current;
 
1396
      } while (e.MoveNext());
 
1397
    }
 
1398
 
 
1399
    /// <summary>
 
1400
    /// Sorts the elements of a sequence in ascending order according to a key.
 
1401
    /// </summary>
 
1402
 
 
1403
    public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
 
1404
      this IEnumerable<TSource> source,
 
1405
      Func<TSource, TKey> keySelector)
 
1406
    {
 
1407
      return source.OrderBy(keySelector, /* comparer */ null);
 
1408
    }
 
1409
 
 
1410
    /// <summary>
 
1411
    /// Sorts the elements of a sequence in ascending order by using a 
 
1412
    /// specified comparer.
 
1413
    /// </summary>
 
1414
 
 
1415
    public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
 
1416
      this IEnumerable<TSource> source,
 
1417
      Func<TSource, TKey> keySelector,
 
1418
      IComparer<TKey> comparer)
 
1419
    {
 
1420
      CheckNotNull(source, "source");
 
1421
      CheckNotNull(keySelector, "keySelector");
 
1422
 
 
1423
      return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ false);
 
1424
    }
 
1425
 
 
1426
    /// <summary>
 
1427
    /// Sorts the elements of a sequence in descending order according to a key.
 
1428
    /// </summary>
 
1429
 
 
1430
    public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
 
1431
      this IEnumerable<TSource> source,
 
1432
      Func<TSource, TKey> keySelector)
 
1433
    {
 
1434
      return source.OrderByDescending(keySelector, /* comparer */ null);
 
1435
    }
 
1436
 
 
1437
    /// <summary>
 
1438
    ///  Sorts the elements of a sequence in descending order by using a 
 
1439
    /// specified comparer. 
 
1440
    /// </summary>
 
1441
 
 
1442
    public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
 
1443
      this IEnumerable<TSource> source,
 
1444
      Func<TSource, TKey> keySelector,
 
1445
      IComparer<TKey> comparer)
 
1446
    {
 
1447
      CheckNotNull(source, "source");
 
1448
      CheckNotNull(source, "keySelector");
 
1449
 
 
1450
      return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ true);
 
1451
    }
 
1452
 
 
1453
    /// <summary>
 
1454
    /// Performs a subsequent ordering of the elements in a sequence in 
 
1455
    /// ascending order according to a key.
 
1456
    /// </summary>
 
1457
 
 
1458
    public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
 
1459
      this IOrderedEnumerable<TSource> source,
 
1460
      Func<TSource, TKey> keySelector)
 
1461
    {
 
1462
      return source.ThenBy(keySelector, /* comparer */ null);
 
1463
    }
 
1464
 
 
1465
    /// <summary>
 
1466
    /// Performs a subsequent ordering of the elements in a sequence in 
 
1467
    /// ascending order by using a specified comparer.
 
1468
    /// </summary>
 
1469
 
 
1470
    public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
 
1471
      this IOrderedEnumerable<TSource> source,
 
1472
      Func<TSource, TKey> keySelector,
 
1473
      IComparer<TKey> comparer)
 
1474
    {
 
1475
      CheckNotNull(source, "source");
 
1476
 
 
1477
      return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ false);
 
1478
    }
 
1479
 
 
1480
    /// <summary>
 
1481
    /// Performs a subsequent ordering of the elements in a sequence in 
 
1482
    /// descending order, according to a key.
 
1483
    /// </summary>
 
1484
 
 
1485
    public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
 
1486
      this IOrderedEnumerable<TSource> source,
 
1487
      Func<TSource, TKey> keySelector)
 
1488
    {
 
1489
      return source.ThenByDescending(keySelector, /* comparer */ null);
 
1490
    }
 
1491
 
 
1492
    /// <summary>
 
1493
    /// Performs a subsequent ordering of the elements in a sequence in 
 
1494
    /// descending order by using a specified comparer.
 
1495
    /// </summary>
 
1496
 
 
1497
    public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
 
1498
      this IOrderedEnumerable<TSource> source,
 
1499
      Func<TSource, TKey> keySelector,
 
1500
      IComparer<TKey> comparer)
 
1501
    {
 
1502
      CheckNotNull(source, "source");
 
1503
 
 
1504
      return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ true);
 
1505
    }
 
1506
 
 
1507
    /// <summary>
 
1508
    /// Base implementation for Intersect and Except operators.
 
1509
    /// </summary>
 
1510
 
 
1511
    private static IEnumerable<TSource> IntersectExceptImpl<TSource>(
 
1512
      this IEnumerable<TSource> first,
 
1513
      IEnumerable<TSource> second,
 
1514
      IEqualityComparer<TSource> comparer,
 
1515
      bool flag)
 
1516
    {
 
1517
      CheckNotNull(first, "first");
 
1518
      CheckNotNull(second, "second");
 
1519
 
 
1520
      var keys = new List<TSource>();
 
1521
      var flags = new Dictionary<TSource, bool>(comparer);
 
1522
 
 
1523
      foreach (var item in first.Where(k => !flags.ContainsKey(k)))
 
1524
      {
 
1525
        flags.Add(item, !flag);
 
1526
        keys.Add(item);
 
1527
      }
 
1528
 
 
1529
      foreach (var item in second.Where(flags.ContainsKey))
 
1530
        flags[item] = flag;
 
1531
 
 
1532
      //
 
1533
      // As per docs, "the marked elements are yielded in the order in 
 
1534
      // which they were collected.
 
1535
      //
 
1536
 
 
1537
      return keys.Where(item => flags[item]);
 
1538
    }
 
1539
 
 
1540
    /// <summary>
 
1541
    /// Produces the set intersection of two sequences by using the 
 
1542
    /// default equality comparer to compare values.
 
1543
    /// </summary>
 
1544
 
 
1545
    public static IEnumerable<TSource> Intersect<TSource>(
 
1546
      this IEnumerable<TSource> first,
 
1547
      IEnumerable<TSource> second)
 
1548
    {
 
1549
      return first.Intersect(second, /* comparer */ null);
 
1550
    }
 
1551
 
 
1552
    /// <summary>
 
1553
    /// Produces the set intersection of two sequences by using the 
 
1554
    /// specified <see cref="IEqualityComparer{T}" /> to compare values.
 
1555
    /// </summary>
 
1556
 
 
1557
    public static IEnumerable<TSource> Intersect<TSource>(
 
1558
      this IEnumerable<TSource> first,
 
1559
      IEnumerable<TSource> second,
 
1560
      IEqualityComparer<TSource> comparer)
 
1561
    {
 
1562
      return IntersectExceptImpl(first, second, comparer, /* flag */ true);
 
1563
    }
 
1564
 
 
1565
    /// <summary>
 
1566
    /// Produces the set difference of two sequences by using the 
 
1567
    /// default equality comparer to compare values.
 
1568
    /// </summary>
 
1569
 
 
1570
    public static IEnumerable<TSource> Except<TSource>(
 
1571
      this IEnumerable<TSource> first,
 
1572
      IEnumerable<TSource> second)
 
1573
    {
 
1574
      return first.Except(second, /* comparer */ null);
 
1575
    }
 
1576
 
 
1577
    /// <summary>
 
1578
    /// Produces the set difference of two sequences by using the 
 
1579
    /// specified <see cref="IEqualityComparer{T}" /> to compare values.
 
1580
    /// </summary>
 
1581
 
 
1582
    public static IEnumerable<TSource> Except<TSource>(
 
1583
      this IEnumerable<TSource> first,
 
1584
      IEnumerable<TSource> second,
 
1585
      IEqualityComparer<TSource> comparer)
 
1586
    {
 
1587
      return IntersectExceptImpl(first, second, comparer, /* flag */ false);
 
1588
    }
 
1589
 
 
1590
    /// <summary>
 
1591
    /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an 
 
1592
    /// <see cref="IEnumerable{T}" /> according to a specified key 
 
1593
    /// selector function.
 
1594
    /// </summary>
 
1595
 
 
1596
    public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
 
1597
      this IEnumerable<TSource> source,
 
1598
      Func<TSource, TKey> keySelector)
 
1599
    {
 
1600
      return source.ToDictionary(keySelector, /* comparer */ null);
 
1601
    }
 
1602
 
 
1603
    /// <summary>
 
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.
 
1607
    /// </summary>
 
1608
 
 
1609
    public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
 
1610
      this IEnumerable<TSource> source,
 
1611
      Func<TSource, TKey> keySelector,
 
1612
      IEqualityComparer<TKey> comparer)
 
1613
    {
 
1614
      return source.ToDictionary(keySelector, e => e);
 
1615
    }
 
1616
 
 
1617
    /// <summary>
 
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.
 
1621
    /// </summary>
 
1622
 
 
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)
 
1627
    {
 
1628
      return source.ToDictionary(keySelector, elementSelector, /* comparer */ null);
 
1629
    }
 
1630
 
 
1631
    /// <summary>
 
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.
 
1635
    /// </summary>
 
1636
 
 
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)
 
1642
    {
 
1643
      CheckNotNull(source, "source");
 
1644
      CheckNotNull(keySelector, "keySelector");
 
1645
      CheckNotNull(elementSelector, "elementSelector");
 
1646
 
 
1647
      var dict = new Dictionary<TKey, TElement>(comparer);
 
1648
 
 
1649
      foreach (var item in source)
 
1650
      {
 
1651
        //
 
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
 
1660
        // lifting.
 
1661
        //
 
1662
 
 
1663
        dict.Add(keySelector(item), elementSelector(item));
 
1664
      }
 
1665
 
 
1666
      return dict;
 
1667
    }
 
1668
 
 
1669
    /// <summary>
 
1670
    /// Correlates the elements of two sequences based on matching keys. 
 
1671
    /// The default equality comparer is used to compare keys.
 
1672
    /// </summary>
 
1673
 
 
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)
 
1680
    {
 
1681
      return outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
 
1682
    }
 
1683
 
 
1684
    /// <summary>
 
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.
 
1688
    /// </summary>
 
1689
 
 
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)
 
1697
    {
 
1698
      CheckNotNull(outer, "outer");
 
1699
      CheckNotNull(inner, "inner");
 
1700
      CheckNotNull(outerKeySelector, "outerKeySelector");
 
1701
      CheckNotNull(innerKeySelector, "innerKeySelector");
 
1702
      CheckNotNull(resultSelector, "resultSelector");
 
1703
 
 
1704
      var lookup = inner.ToLookup(innerKeySelector, comparer);
 
1705
 
 
1706
      return
 
1707
        from o in outer
 
1708
        from i in lookup[outerKeySelector(o)]
 
1709
        select resultSelector(o, i);
 
1710
    }
 
1711
 
 
1712
    /// <summary>
 
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.
 
1716
    /// </summary>
 
1717
 
 
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)
 
1724
    {
 
1725
      return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null);
 
1726
    }
 
1727
 
 
1728
    /// <summary>
 
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.
 
1733
    /// </summary>
 
1734
 
 
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)
 
1742
    {
 
1743
      CheckNotNull(outer, "outer");
 
1744
      CheckNotNull(inner, "inner");
 
1745
      CheckNotNull(outerKeySelector, "outerKeySelector");
 
1746
      CheckNotNull(innerKeySelector, "innerKeySelector");
 
1747
      CheckNotNull(resultSelector, "resultSelector");
 
1748
 
 
1749
      var lookup = inner.ToLookup(innerKeySelector, comparer);
 
1750
      return outer.Select(o => resultSelector(o, lookup[outerKeySelector(o)]));
 
1751
    }
 
1752
 
 
1753
    [DebuggerStepThrough]
 
1754
    private static void CheckNotNull<T>(T value, string name) where T : class
 
1755
    {
 
1756
      if (value == null)
 
1757
        throw new ArgumentNullException(name);
 
1758
    }
 
1759
 
 
1760
    private static class Sequence<T>
 
1761
    {
 
1762
      public static readonly IEnumerable<T> Empty = new T[0];
 
1763
    }
 
1764
 
 
1765
    private sealed class Grouping<K, V> : List<V>, IGrouping<K, V>
 
1766
    {
 
1767
      internal Grouping(K key)
 
1768
      {
 
1769
        Key = key;
 
1770
      }
 
1771
 
 
1772
      public K Key { get; private set; }
 
1773
    }
 
1774
  }
 
1775
 
 
1776
  internal partial class Enumerable
 
1777
  {
 
1778
    /// <summary>
 
1779
    /// Computes the sum of a sequence of nullable <see cref="System.Int32" /> values.
 
1780
    /// </summary>
 
1781
 
 
1782
    public static int Sum(
 
1783
      this IEnumerable<int> source)
 
1784
    {
 
1785
      CheckNotNull(source, "source");
 
1786
 
 
1787
      int sum = 0;
 
1788
      foreach (var num in source)
 
1789
        sum = checked(sum + num);
 
1790
 
 
1791
      return sum;
 
1792
    }
 
1793
 
 
1794
    /// <summary>
 
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.
 
1798
    /// </summary>
 
1799
 
 
1800
    public static int Sum<TSource>(
 
1801
      this IEnumerable<TSource> source,
 
1802
      Func<TSource, int> selector)
 
1803
    {
 
1804
      return source.Select(selector).Sum();
 
1805
    }
 
1806
 
 
1807
    /// <summary>
 
1808
    /// Computes the average of a sequence of nullable <see cref="System.Int32" /> values.
 
1809
    /// </summary>
 
1810
 
 
1811
    public static double Average(
 
1812
      this IEnumerable<int> source)
 
1813
    {
 
1814
      CheckNotNull(source, "source");
 
1815
 
 
1816
      long sum = 0;
 
1817
      long count = 0;
 
1818
 
 
1819
      foreach (var num in source)
 
1820
        checked
 
1821
        {
 
1822
          sum += (int) num;
 
1823
          count++;
 
1824
        }
 
1825
 
 
1826
      if (count == 0)
 
1827
        throw new InvalidOperationException();
 
1828
 
 
1829
      return (double) sum/count;
 
1830
    }
 
1831
 
 
1832
    /// <summary>
 
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.
 
1836
    /// </summary>
 
1837
 
 
1838
    public static double Average<TSource>(
 
1839
      this IEnumerable<TSource> source,
 
1840
      Func<TSource, int> selector)
 
1841
    {
 
1842
      return source.Select(selector).Average();
 
1843
    }
 
1844
 
 
1845
 
 
1846
    /// <summary>
 
1847
    /// Computes the sum of a sequence of <see cref="System.Int32" /> values.
 
1848
    /// </summary>
 
1849
 
 
1850
    public static int? Sum(
 
1851
      this IEnumerable<int?> source)
 
1852
    {
 
1853
      CheckNotNull(source, "source");
 
1854
 
 
1855
      int sum = 0;
 
1856
      foreach (var num in source)
 
1857
        sum = checked(sum + (num ?? 0));
 
1858
 
 
1859
      return sum;
 
1860
    }
 
1861
 
 
1862
    /// <summary>
 
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.
 
1866
    /// </summary>
 
1867
 
 
1868
    public static int? Sum<TSource>(
 
1869
      this IEnumerable<TSource> source,
 
1870
      Func<TSource, int?> selector)
 
1871
    {
 
1872
      return source.Select(selector).Sum();
 
1873
    }
 
1874
 
 
1875
    /// <summary>
 
1876
    /// Computes the average of a sequence of <see cref="System.Int32" /> values.
 
1877
    /// </summary>
 
1878
 
 
1879
    public static double? Average(
 
1880
      this IEnumerable<int?> source)
 
1881
    {
 
1882
      CheckNotNull(source, "source");
 
1883
 
 
1884
      long sum = 0;
 
1885
      long count = 0;
 
1886
 
 
1887
      foreach (var num in source.Where(n => n != null))
 
1888
        checked
 
1889
        {
 
1890
          sum += (int) num;
 
1891
          count++;
 
1892
        }
 
1893
 
 
1894
      if (count == 0)
 
1895
        return null;
 
1896
 
 
1897
      return (double?) sum/count;
 
1898
    }
 
1899
 
 
1900
    /// <summary>
 
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.
 
1904
    /// </summary>
 
1905
 
 
1906
    public static double? Average<TSource>(
 
1907
      this IEnumerable<TSource> source,
 
1908
      Func<TSource, int?> selector)
 
1909
    {
 
1910
      return source.Select(selector).Average();
 
1911
    }
 
1912
 
 
1913
    /// <summary>
 
1914
    /// Returns the minimum value in a sequence of nullable 
 
1915
    /// <see cref="System.Int32" /> values.
 
1916
    /// </summary>
 
1917
 
 
1918
    public static int? Min(
 
1919
      this IEnumerable<int?> source)
 
1920
    {
 
1921
      CheckNotNull(source, "source");
 
1922
 
 
1923
      return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
 
1924
    }
 
1925
 
 
1926
    /// <summary>
 
1927
    /// Invokes a transform function on each element of a sequence and 
 
1928
    /// returns the minimum nullable <see cref="System.Int32" /> value.
 
1929
    /// </summary>
 
1930
 
 
1931
    public static int? Min<TSource>(
 
1932
      this IEnumerable<TSource> source,
 
1933
      Func<TSource, int?> selector)
 
1934
    {
 
1935
      return source.Select(selector).Min();
 
1936
    }
 
1937
 
 
1938
    /// <summary>
 
1939
    /// Returns the maximum value in a sequence of nullable 
 
1940
    /// <see cref="System.Int32" /> values.
 
1941
    /// </summary>
 
1942
 
 
1943
    public static int? Max(
 
1944
      this IEnumerable<int?> source)
 
1945
    {
 
1946
      CheckNotNull(source, "source");
 
1947
 
 
1948
      return MinMaxImpl(source.Where(x => x != null),
 
1949
                        null, (max, x) => x == null || (max != null && x.Value < max.Value));
 
1950
    }
 
1951
 
 
1952
    /// <summary>
 
1953
    /// Invokes a transform function on each element of a sequence and 
 
1954
    /// returns the maximum nullable <see cref="System.Int32" /> value.
 
1955
    /// </summary>
 
1956
 
 
1957
    public static int? Max<TSource>(
 
1958
      this IEnumerable<TSource> source,
 
1959
      Func<TSource, int?> selector)
 
1960
    {
 
1961
      return source.Select(selector).Max();
 
1962
    }
 
1963
 
 
1964
    /// <summary>
 
1965
    /// Computes the sum of a sequence of nullable <see cref="System.Int64" /> values.
 
1966
    /// </summary>
 
1967
 
 
1968
    public static long Sum(
 
1969
      this IEnumerable<long> source)
 
1970
    {
 
1971
      CheckNotNull(source, "source");
 
1972
 
 
1973
      long sum = 0;
 
1974
      foreach (var num in source)
 
1975
        sum = checked(sum + num);
 
1976
 
 
1977
      return sum;
 
1978
    }
 
1979
 
 
1980
    /// <summary>
 
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.
 
1984
    /// </summary>
 
1985
 
 
1986
    public static long Sum<TSource>(
 
1987
      this IEnumerable<TSource> source,
 
1988
      Func<TSource, long> selector)
 
1989
    {
 
1990
      return source.Select(selector).Sum();
 
1991
    }
 
1992
 
 
1993
    /// <summary>
 
1994
    /// Computes the average of a sequence of nullable <see cref="System.Int64" /> values.
 
1995
    /// </summary>
 
1996
 
 
1997
    public static double Average(
 
1998
      this IEnumerable<long> source)
 
1999
    {
 
2000
      CheckNotNull(source, "source");
 
2001
 
 
2002
      long sum = 0;
 
2003
      long count = 0;
 
2004
 
 
2005
      foreach (var num in source)
 
2006
        checked
 
2007
        {
 
2008
          sum += (long) num;
 
2009
          count++;
 
2010
        }
 
2011
 
 
2012
      if (count == 0)
 
2013
        throw new InvalidOperationException();
 
2014
 
 
2015
      return (double) sum/count;
 
2016
    }
 
2017
 
 
2018
    /// <summary>
 
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.
 
2022
    /// </summary>
 
2023
 
 
2024
    public static double Average<TSource>(
 
2025
      this IEnumerable<TSource> source,
 
2026
      Func<TSource, long> selector)
 
2027
    {
 
2028
      return source.Select(selector).Average();
 
2029
    }
 
2030
 
 
2031
 
 
2032
    /// <summary>
 
2033
    /// Computes the sum of a sequence of <see cref="System.Int64" /> values.
 
2034
    /// </summary>
 
2035
 
 
2036
    public static long? Sum(
 
2037
      this IEnumerable<long?> source)
 
2038
    {
 
2039
      CheckNotNull(source, "source");
 
2040
 
 
2041
      long sum = 0;
 
2042
      foreach (var num in source)
 
2043
        sum = checked(sum + (num ?? 0));
 
2044
 
 
2045
      return sum;
 
2046
    }
 
2047
 
 
2048
    /// <summary>
 
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.
 
2052
    /// </summary>
 
2053
 
 
2054
    public static long? Sum<TSource>(
 
2055
      this IEnumerable<TSource> source,
 
2056
      Func<TSource, long?> selector)
 
2057
    {
 
2058
      return source.Select(selector).Sum();
 
2059
    }
 
2060
 
 
2061
    /// <summary>
 
2062
    /// Computes the average of a sequence of <see cref="System.Int64" /> values.
 
2063
    /// </summary>
 
2064
 
 
2065
    public static double? Average(
 
2066
      this IEnumerable<long?> source)
 
2067
    {
 
2068
      CheckNotNull(source, "source");
 
2069
 
 
2070
      long sum = 0;
 
2071
      long count = 0;
 
2072
 
 
2073
      foreach (var num in source.Where(n => n != null))
 
2074
        checked
 
2075
        {
 
2076
          sum += (long) num;
 
2077
          count++;
 
2078
        }
 
2079
 
 
2080
      if (count == 0)
 
2081
        return null;
 
2082
 
 
2083
      return (double?) sum/count;
 
2084
    }
 
2085
 
 
2086
    /// <summary>
 
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.
 
2090
    /// </summary>
 
2091
 
 
2092
    public static double? Average<TSource>(
 
2093
      this IEnumerable<TSource> source,
 
2094
      Func<TSource, long?> selector)
 
2095
    {
 
2096
      return source.Select(selector).Average();
 
2097
    }
 
2098
 
 
2099
    /// <summary>
 
2100
    /// Returns the minimum value in a sequence of nullable 
 
2101
    /// <see cref="System.Int64" /> values.
 
2102
    /// </summary>
 
2103
 
 
2104
    public static long? Min(
 
2105
      this IEnumerable<long?> source)
 
2106
    {
 
2107
      CheckNotNull(source, "source");
 
2108
 
 
2109
      return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
 
2110
    }
 
2111
 
 
2112
    /// <summary>
 
2113
    /// Invokes a transform function on each element of a sequence and 
 
2114
    /// returns the minimum nullable <see cref="System.Int64" /> value.
 
2115
    /// </summary>
 
2116
 
 
2117
    public static long? Min<TSource>(
 
2118
      this IEnumerable<TSource> source,
 
2119
      Func<TSource, long?> selector)
 
2120
    {
 
2121
      return source.Select(selector).Min();
 
2122
    }
 
2123
 
 
2124
    /// <summary>
 
2125
    /// Returns the maximum value in a sequence of nullable 
 
2126
    /// <see cref="System.Int64" /> values.
 
2127
    /// </summary>
 
2128
 
 
2129
    public static long? Max(
 
2130
      this IEnumerable<long?> source)
 
2131
    {
 
2132
      CheckNotNull(source, "source");
 
2133
 
 
2134
      return MinMaxImpl(source.Where(x => x != null),
 
2135
                        null, (max, x) => x == null || (max != null && x.Value < max.Value));
 
2136
    }
 
2137
 
 
2138
    /// <summary>
 
2139
    /// Invokes a transform function on each element of a sequence and 
 
2140
    /// returns the maximum nullable <see cref="System.Int64" /> value.
 
2141
    /// </summary>
 
2142
 
 
2143
    public static long? Max<TSource>(
 
2144
      this IEnumerable<TSource> source,
 
2145
      Func<TSource, long?> selector)
 
2146
    {
 
2147
      return source.Select(selector).Max();
 
2148
    }
 
2149
 
 
2150
    /// <summary>
 
2151
    /// Computes the sum of a sequence of nullable <see cref="System.Single" /> values.
 
2152
    /// </summary>
 
2153
 
 
2154
    public static float Sum(
 
2155
      this IEnumerable<float> source)
 
2156
    {
 
2157
      CheckNotNull(source, "source");
 
2158
 
 
2159
      float sum = 0;
 
2160
      foreach (var num in source)
 
2161
        sum = checked(sum + num);
 
2162
 
 
2163
      return sum;
 
2164
    }
 
2165
 
 
2166
    /// <summary>
 
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.
 
2170
    /// </summary>
 
2171
 
 
2172
    public static float Sum<TSource>(
 
2173
      this IEnumerable<TSource> source,
 
2174
      Func<TSource, float> selector)
 
2175
    {
 
2176
      return source.Select(selector).Sum();
 
2177
    }
 
2178
 
 
2179
    /// <summary>
 
2180
    /// Computes the average of a sequence of nullable <see cref="System.Single" /> values.
 
2181
    /// </summary>
 
2182
 
 
2183
    public static float Average(
 
2184
      this IEnumerable<float> source)
 
2185
    {
 
2186
      CheckNotNull(source, "source");
 
2187
 
 
2188
      float sum = 0;
 
2189
      long count = 0;
 
2190
 
 
2191
      foreach (var num in source)
 
2192
        checked
 
2193
        {
 
2194
          sum += (float) num;
 
2195
          count++;
 
2196
        }
 
2197
 
 
2198
      if (count == 0)
 
2199
        throw new InvalidOperationException();
 
2200
 
 
2201
      return (float) sum/count;
 
2202
    }
 
2203
 
 
2204
    /// <summary>
 
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.
 
2208
    /// </summary>
 
2209
 
 
2210
    public static float Average<TSource>(
 
2211
      this IEnumerable<TSource> source,
 
2212
      Func<TSource, float> selector)
 
2213
    {
 
2214
      return source.Select(selector).Average();
 
2215
    }
 
2216
 
 
2217
 
 
2218
    /// <summary>
 
2219
    /// Computes the sum of a sequence of <see cref="System.Single" /> values.
 
2220
    /// </summary>
 
2221
 
 
2222
    public static float? Sum(
 
2223
      this IEnumerable<float?> source)
 
2224
    {
 
2225
      CheckNotNull(source, "source");
 
2226
 
 
2227
      float sum = 0;
 
2228
      foreach (var num in source)
 
2229
        sum = checked(sum + (num ?? 0));
 
2230
 
 
2231
      return sum;
 
2232
    }
 
2233
 
 
2234
    /// <summary>
 
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.
 
2238
    /// </summary>
 
2239
 
 
2240
    public static float? Sum<TSource>(
 
2241
      this IEnumerable<TSource> source,
 
2242
      Func<TSource, float?> selector)
 
2243
    {
 
2244
      return source.Select(selector).Sum();
 
2245
    }
 
2246
 
 
2247
    /// <summary>
 
2248
    /// Computes the average of a sequence of <see cref="System.Single" /> values.
 
2249
    /// </summary>
 
2250
 
 
2251
    public static float? Average(
 
2252
      this IEnumerable<float?> source)
 
2253
    {
 
2254
      CheckNotNull(source, "source");
 
2255
 
 
2256
      float sum = 0;
 
2257
      long count = 0;
 
2258
 
 
2259
      foreach (var num in source.Where(n => n != null))
 
2260
        checked
 
2261
        {
 
2262
          sum += (float) num;
 
2263
          count++;
 
2264
        }
 
2265
 
 
2266
      if (count == 0)
 
2267
        return null;
 
2268
 
 
2269
      return (float?) sum/count;
 
2270
    }
 
2271
 
 
2272
    /// <summary>
 
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.
 
2276
    /// </summary>
 
2277
 
 
2278
    public static float? Average<TSource>(
 
2279
      this IEnumerable<TSource> source,
 
2280
      Func<TSource, float?> selector)
 
2281
    {
 
2282
      return source.Select(selector).Average();
 
2283
    }
 
2284
 
 
2285
    /// <summary>
 
2286
    /// Returns the minimum value in a sequence of nullable 
 
2287
    /// <see cref="System.Single" /> values.
 
2288
    /// </summary>
 
2289
 
 
2290
    public static float? Min(
 
2291
      this IEnumerable<float?> source)
 
2292
    {
 
2293
      CheckNotNull(source, "source");
 
2294
 
 
2295
      return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
 
2296
    }
 
2297
 
 
2298
    /// <summary>
 
2299
    /// Invokes a transform function on each element of a sequence and 
 
2300
    /// returns the minimum nullable <see cref="System.Single" /> value.
 
2301
    /// </summary>
 
2302
 
 
2303
    public static float? Min<TSource>(
 
2304
      this IEnumerable<TSource> source,
 
2305
      Func<TSource, float?> selector)
 
2306
    {
 
2307
      return source.Select(selector).Min();
 
2308
    }
 
2309
 
 
2310
    /// <summary>
 
2311
    /// Returns the maximum value in a sequence of nullable 
 
2312
    /// <see cref="System.Single" /> values.
 
2313
    /// </summary>
 
2314
 
 
2315
    public static float? Max(
 
2316
      this IEnumerable<float?> source)
 
2317
    {
 
2318
      CheckNotNull(source, "source");
 
2319
 
 
2320
      return MinMaxImpl(source.Where(x => x != null),
 
2321
                        null, (max, x) => x == null || (max != null && x.Value < max.Value));
 
2322
    }
 
2323
 
 
2324
    /// <summary>
 
2325
    /// Invokes a transform function on each element of a sequence and 
 
2326
    /// returns the maximum nullable <see cref="System.Single" /> value.
 
2327
    /// </summary>
 
2328
 
 
2329
    public static float? Max<TSource>(
 
2330
      this IEnumerable<TSource> source,
 
2331
      Func<TSource, float?> selector)
 
2332
    {
 
2333
      return source.Select(selector).Max();
 
2334
    }
 
2335
 
 
2336
    /// <summary>
 
2337
    /// Computes the sum of a sequence of nullable <see cref="System.Double" /> values.
 
2338
    /// </summary>
 
2339
 
 
2340
    public static double Sum(
 
2341
      this IEnumerable<double> source)
 
2342
    {
 
2343
      CheckNotNull(source, "source");
 
2344
 
 
2345
      double sum = 0;
 
2346
      foreach (var num in source)
 
2347
        sum = checked(sum + num);
 
2348
 
 
2349
      return sum;
 
2350
    }
 
2351
 
 
2352
    /// <summary>
 
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.
 
2356
    /// </summary>
 
2357
 
 
2358
    public static double Sum<TSource>(
 
2359
      this IEnumerable<TSource> source,
 
2360
      Func<TSource, double> selector)
 
2361
    {
 
2362
      return source.Select(selector).Sum();
 
2363
    }
 
2364
 
 
2365
    /// <summary>
 
2366
    /// Computes the average of a sequence of nullable <see cref="System.Double" /> values.
 
2367
    /// </summary>
 
2368
 
 
2369
    public static double Average(
 
2370
      this IEnumerable<double> source)
 
2371
    {
 
2372
      CheckNotNull(source, "source");
 
2373
 
 
2374
      double sum = 0;
 
2375
      long count = 0;
 
2376
 
 
2377
      foreach (var num in source)
 
2378
        checked
 
2379
        {
 
2380
          sum += (double) num;
 
2381
          count++;
 
2382
        }
 
2383
 
 
2384
      if (count == 0)
 
2385
        throw new InvalidOperationException();
 
2386
 
 
2387
      return (double) sum/count;
 
2388
    }
 
2389
 
 
2390
    /// <summary>
 
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.
 
2394
    /// </summary>
 
2395
 
 
2396
    public static double Average<TSource>(
 
2397
      this IEnumerable<TSource> source,
 
2398
      Func<TSource, double> selector)
 
2399
    {
 
2400
      return source.Select(selector).Average();
 
2401
    }
 
2402
 
 
2403
 
 
2404
    /// <summary>
 
2405
    /// Computes the sum of a sequence of <see cref="System.Double" /> values.
 
2406
    /// </summary>
 
2407
 
 
2408
    public static double? Sum(
 
2409
      this IEnumerable<double?> source)
 
2410
    {
 
2411
      CheckNotNull(source, "source");
 
2412
 
 
2413
      double sum = 0;
 
2414
      foreach (var num in source)
 
2415
        sum = checked(sum + (num ?? 0));
 
2416
 
 
2417
      return sum;
 
2418
    }
 
2419
 
 
2420
    /// <summary>
 
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.
 
2424
    /// </summary>
 
2425
 
 
2426
    public static double? Sum<TSource>(
 
2427
      this IEnumerable<TSource> source,
 
2428
      Func<TSource, double?> selector)
 
2429
    {
 
2430
      return source.Select(selector).Sum();
 
2431
    }
 
2432
 
 
2433
    /// <summary>
 
2434
    /// Computes the average of a sequence of <see cref="System.Double" /> values.
 
2435
    /// </summary>
 
2436
 
 
2437
    public static double? Average(
 
2438
      this IEnumerable<double?> source)
 
2439
    {
 
2440
      CheckNotNull(source, "source");
 
2441
 
 
2442
      double sum = 0;
 
2443
      long count = 0;
 
2444
 
 
2445
      foreach (var num in source.Where(n => n != null))
 
2446
        checked
 
2447
        {
 
2448
          sum += (double) num;
 
2449
          count++;
 
2450
        }
 
2451
 
 
2452
      if (count == 0)
 
2453
        return null;
 
2454
 
 
2455
      return (double?) sum/count;
 
2456
    }
 
2457
 
 
2458
    /// <summary>
 
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.
 
2462
    /// </summary>
 
2463
 
 
2464
    public static double? Average<TSource>(
 
2465
      this IEnumerable<TSource> source,
 
2466
      Func<TSource, double?> selector)
 
2467
    {
 
2468
      return source.Select(selector).Average();
 
2469
    }
 
2470
 
 
2471
    /// <summary>
 
2472
    /// Returns the minimum value in a sequence of nullable 
 
2473
    /// <see cref="System.Double" /> values.
 
2474
    /// </summary>
 
2475
 
 
2476
    public static double? Min(
 
2477
      this IEnumerable<double?> source)
 
2478
    {
 
2479
      CheckNotNull(source, "source");
 
2480
 
 
2481
      return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
 
2482
    }
 
2483
 
 
2484
    /// <summary>
 
2485
    /// Invokes a transform function on each element of a sequence and 
 
2486
    /// returns the minimum nullable <see cref="System.Double" /> value.
 
2487
    /// </summary>
 
2488
 
 
2489
    public static double? Min<TSource>(
 
2490
      this IEnumerable<TSource> source,
 
2491
      Func<TSource, double?> selector)
 
2492
    {
 
2493
      return source.Select(selector).Min();
 
2494
    }
 
2495
 
 
2496
    /// <summary>
 
2497
    /// Returns the maximum value in a sequence of nullable 
 
2498
    /// <see cref="System.Double" /> values.
 
2499
    /// </summary>
 
2500
 
 
2501
    public static double? Max(
 
2502
      this IEnumerable<double?> source)
 
2503
    {
 
2504
      CheckNotNull(source, "source");
 
2505
 
 
2506
      return MinMaxImpl(source.Where(x => x != null),
 
2507
                        null, (max, x) => x == null || (max != null && x.Value < max.Value));
 
2508
    }
 
2509
 
 
2510
    /// <summary>
 
2511
    /// Invokes a transform function on each element of a sequence and 
 
2512
    /// returns the maximum nullable <see cref="System.Double" /> value.
 
2513
    /// </summary>
 
2514
 
 
2515
    public static double? Max<TSource>(
 
2516
      this IEnumerable<TSource> source,
 
2517
      Func<TSource, double?> selector)
 
2518
    {
 
2519
      return source.Select(selector).Max();
 
2520
    }
 
2521
 
 
2522
    /// <summary>
 
2523
    /// Computes the sum of a sequence of nullable <see cref="System.Decimal" /> values.
 
2524
    /// </summary>
 
2525
 
 
2526
    public static decimal Sum(
 
2527
      this IEnumerable<decimal> source)
 
2528
    {
 
2529
      CheckNotNull(source, "source");
 
2530
 
 
2531
      decimal sum = 0;
 
2532
      foreach (var num in source)
 
2533
        sum = checked(sum + num);
 
2534
 
 
2535
      return sum;
 
2536
    }
 
2537
 
 
2538
    /// <summary>
 
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.
 
2542
    /// </summary>
 
2543
 
 
2544
    public static decimal Sum<TSource>(
 
2545
      this IEnumerable<TSource> source,
 
2546
      Func<TSource, decimal> selector)
 
2547
    {
 
2548
      return source.Select(selector).Sum();
 
2549
    }
 
2550
 
 
2551
    /// <summary>
 
2552
    /// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values.
 
2553
    /// </summary>
 
2554
 
 
2555
    public static decimal Average(
 
2556
      this IEnumerable<decimal> source)
 
2557
    {
 
2558
      CheckNotNull(source, "source");
 
2559
 
 
2560
      decimal sum = 0;
 
2561
      long count = 0;
 
2562
 
 
2563
      foreach (var num in source)
 
2564
        checked
 
2565
        {
 
2566
          sum += (decimal) num;
 
2567
          count++;
 
2568
        }
 
2569
 
 
2570
      if (count == 0)
 
2571
        throw new InvalidOperationException();
 
2572
 
 
2573
      return (decimal) sum/count;
 
2574
    }
 
2575
 
 
2576
    /// <summary>
 
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.
 
2580
    /// </summary>
 
2581
 
 
2582
    public static decimal Average<TSource>(
 
2583
      this IEnumerable<TSource> source,
 
2584
      Func<TSource, decimal> selector)
 
2585
    {
 
2586
      return source.Select(selector).Average();
 
2587
    }
 
2588
 
 
2589
 
 
2590
    /// <summary>
 
2591
    /// Computes the sum of a sequence of <see cref="System.Decimal" /> values.
 
2592
    /// </summary>
 
2593
 
 
2594
    public static decimal? Sum(
 
2595
      this IEnumerable<decimal?> source)
 
2596
    {
 
2597
      CheckNotNull(source, "source");
 
2598
 
 
2599
      decimal sum = 0;
 
2600
      foreach (var num in source)
 
2601
        sum = checked(sum + (num ?? 0));
 
2602
 
 
2603
      return sum;
 
2604
    }
 
2605
 
 
2606
    /// <summary>
 
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.
 
2610
    /// </summary>
 
2611
 
 
2612
    public static decimal? Sum<TSource>(
 
2613
      this IEnumerable<TSource> source,
 
2614
      Func<TSource, decimal?> selector)
 
2615
    {
 
2616
      return source.Select(selector).Sum();
 
2617
    }
 
2618
 
 
2619
    /// <summary>
 
2620
    /// Computes the average of a sequence of <see cref="System.Decimal" /> values.
 
2621
    /// </summary>
 
2622
 
 
2623
    public static decimal? Average(
 
2624
      this IEnumerable<decimal?> source)
 
2625
    {
 
2626
      CheckNotNull(source, "source");
 
2627
 
 
2628
      decimal sum = 0;
 
2629
      long count = 0;
 
2630
 
 
2631
      foreach (var num in source.Where(n => n != null))
 
2632
        checked
 
2633
        {
 
2634
          sum += (decimal) num;
 
2635
          count++;
 
2636
        }
 
2637
 
 
2638
      if (count == 0)
 
2639
        return null;
 
2640
 
 
2641
      return (decimal?) sum/count;
 
2642
    }
 
2643
 
 
2644
    /// <summary>
 
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.
 
2648
    /// </summary>
 
2649
 
 
2650
    public static decimal? Average<TSource>(
 
2651
      this IEnumerable<TSource> source,
 
2652
      Func<TSource, decimal?> selector)
 
2653
    {
 
2654
      return source.Select(selector).Average();
 
2655
    }
 
2656
 
 
2657
    /// <summary>
 
2658
    /// Returns the minimum value in a sequence of nullable 
 
2659
    /// <see cref="System.Decimal" /> values.
 
2660
    /// </summary>
 
2661
 
 
2662
    public static decimal? Min(
 
2663
      this IEnumerable<decimal?> source)
 
2664
    {
 
2665
      CheckNotNull(source, "source");
 
2666
 
 
2667
      return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x);
 
2668
    }
 
2669
 
 
2670
    /// <summary>
 
2671
    /// Invokes a transform function on each element of a sequence and 
 
2672
    /// returns the minimum nullable <see cref="System.Decimal" /> value.
 
2673
    /// </summary>
 
2674
 
 
2675
    public static decimal? Min<TSource>(
 
2676
      this IEnumerable<TSource> source,
 
2677
      Func<TSource, decimal?> selector)
 
2678
    {
 
2679
      return source.Select(selector).Min();
 
2680
    }
 
2681
 
 
2682
    /// <summary>
 
2683
    /// Returns the maximum value in a sequence of nullable 
 
2684
    /// <see cref="System.Decimal" /> values.
 
2685
    /// </summary>
 
2686
 
 
2687
    public static decimal? Max(
 
2688
      this IEnumerable<decimal?> source)
 
2689
    {
 
2690
      CheckNotNull(source, "source");
 
2691
 
 
2692
      return MinMaxImpl(source.Where(x => x != null),
 
2693
                        null, (max, x) => x == null || (max != null && x.Value < max.Value));
 
2694
    }
 
2695
 
 
2696
    /// <summary>
 
2697
    /// Invokes a transform function on each element of a sequence and 
 
2698
    /// returns the maximum nullable <see cref="System.Decimal" /> value.
 
2699
    /// </summary>
 
2700
 
 
2701
    public static decimal? Max<TSource>(
 
2702
      this IEnumerable<TSource> source,
 
2703
      Func<TSource, decimal?> selector)
 
2704
    {
 
2705
      return source.Select(selector).Max();
 
2706
    }
 
2707
  }
 
2708
 
 
2709
  /// <summary>
 
2710
  /// Represents a collection of objects that have a common key.
 
2711
  /// </summary>
 
2712
  internal partial interface IGrouping<TKey, TElement> : IEnumerable<TElement>
 
2713
  {
 
2714
    /// <summary>
 
2715
    /// Gets the key of the <see cref="IGrouping{TKey,TElement}" />.
 
2716
    /// </summary>
 
2717
 
 
2718
    TKey Key { get; }
 
2719
  }
 
2720
 
 
2721
  /// <summary>
 
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.
 
2725
  /// </summary>
 
2726
  internal partial interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
 
2727
  {
 
2728
    bool Contains(TKey key);
 
2729
    int Count { get; }
 
2730
    IEnumerable<TElement> this[TKey key] { get; }
 
2731
  }
 
2732
 
 
2733
  /// <summary>
 
2734
  /// Represents a sorted sequence.
 
2735
  /// </summary>
 
2736
  internal partial interface IOrderedEnumerable<TElement> : IEnumerable<TElement>
 
2737
  {
 
2738
    /// <summary>
 
2739
    /// Performs a subsequent ordering on the elements of an 
 
2740
    /// <see cref="IOrderedEnumerable{T}"/> according to a key.
 
2741
    /// </summary>
 
2742
 
 
2743
    IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(
 
2744
      Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
 
2745
  }
 
2746
 
 
2747
  /// <summary>
 
2748
  /// Represents a collection of keys each mapped to one or more values.
 
2749
  /// </summary>
 
2750
  internal sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement>
 
2751
  {
 
2752
    private readonly Dictionary<TKey, IGrouping<TKey, TElement>> _map;
 
2753
 
 
2754
    internal Lookup(IEqualityComparer<TKey> comparer)
 
2755
    {
 
2756
      _map = new Dictionary<TKey, IGrouping<TKey, TElement>>(comparer);
 
2757
    }
 
2758
 
 
2759
    internal void Add(IGrouping<TKey, TElement> item)
 
2760
    {
 
2761
      _map.Add(item.Key, item);
 
2762
    }
 
2763
 
 
2764
    internal IEnumerable<TElement> Find(TKey key)
 
2765
    {
 
2766
      IGrouping<TKey, TElement> grouping;
 
2767
      return _map.TryGetValue(key, out grouping) ? grouping : null;
 
2768
    }
 
2769
 
 
2770
    /// <summary>
 
2771
    /// Gets the number of key/value collection pairs in the <see cref="Lookup{TKey,TElement}" />.
 
2772
    /// </summary>
 
2773
 
 
2774
    public int Count
 
2775
    {
 
2776
      get { return _map.Count; }
 
2777
    }
 
2778
 
 
2779
    /// <summary>
 
2780
    /// Gets the collection of values indexed by the specified key.
 
2781
    /// </summary>
 
2782
 
 
2783
    public IEnumerable<TElement> this[TKey key]
 
2784
    {
 
2785
      get
 
2786
      {
 
2787
        IGrouping<TKey, TElement> result;
 
2788
        return _map.TryGetValue(key, out result) ? result : Enumerable.Empty<TElement>();
 
2789
      }
 
2790
    }
 
2791
 
 
2792
    /// <summary>
 
2793
    /// Determines whether a specified key is in the <see cref="Lookup{TKey,TElement}" />.
 
2794
    /// </summary>
 
2795
 
 
2796
    public bool Contains(TKey key)
 
2797
    {
 
2798
      return _map.ContainsKey(key);
 
2799
    }
 
2800
 
 
2801
    /// <summary>
 
2802
    /// Applies a transform function to each key and its associated 
 
2803
    /// values and returns the results.
 
2804
    /// </summary>
 
2805
 
 
2806
    public IEnumerable<TResult> ApplyResultSelector<TResult>(
 
2807
      Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
 
2808
    {
 
2809
      if (resultSelector == null)
 
2810
        throw new ArgumentNullException("resultSelector");
 
2811
 
 
2812
      foreach (var pair in _map)
 
2813
        yield return resultSelector(pair.Key, pair.Value);
 
2814
    }
 
2815
 
 
2816
    /// <summary>
 
2817
    /// Returns a generic enumerator that iterates through the <see cref="Lookup{TKey,TElement}" />.
 
2818
    /// </summary>
 
2819
 
 
2820
    public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
 
2821
    {
 
2822
      return _map.Values.GetEnumerator();
 
2823
    }
 
2824
 
 
2825
    IEnumerator IEnumerable.GetEnumerator()
 
2826
    {
 
2827
      return GetEnumerator();
 
2828
    }
 
2829
  }
 
2830
 
 
2831
  internal sealed class OrderedEnumerable<T, K> : IOrderedEnumerable<T>
 
2832
  {
 
2833
    private readonly IEnumerable<T> _source;
 
2834
    private readonly List<Comparison<T>> _comparisons;
 
2835
 
 
2836
    public OrderedEnumerable(IEnumerable<T> source,
 
2837
                             Func<T, K> keySelector, IComparer<K> comparer, bool descending) :
 
2838
                               this(source, null, keySelector, comparer, descending)
 
2839
    {
 
2840
    }
 
2841
 
 
2842
    private OrderedEnumerable(IEnumerable<T> source, List<Comparison<T>> comparisons,
 
2843
                              Func<T, K> keySelector, IComparer<K> comparer, bool descending)
 
2844
    {
 
2845
      if (source == null) throw new ArgumentNullException("source");
 
2846
      if (keySelector == null) throw new ArgumentNullException("keySelector");
 
2847
 
 
2848
      _source = source;
 
2849
 
 
2850
      comparer = comparer ?? Comparer<K>.Default;
 
2851
 
 
2852
      if (comparisons == null)
 
2853
        comparisons = new List<Comparison<T>>( /* capacity */ 4);
 
2854
 
 
2855
      comparisons.Add((x, y)
 
2856
                      => (descending ? -1 : 1)*comparer.Compare(keySelector(x), keySelector(y)));
 
2857
 
 
2858
      _comparisons = comparisons;
 
2859
    }
 
2860
 
 
2861
    public IOrderedEnumerable<T> CreateOrderedEnumerable<KK>(
 
2862
      Func<T, KK> keySelector, IComparer<KK> comparer, bool descending)
 
2863
    {
 
2864
      return new OrderedEnumerable<T, KK>(_source, _comparisons, keySelector, comparer, descending);
 
2865
    }
 
2866
 
 
2867
    public IEnumerator<T> GetEnumerator()
 
2868
    {
 
2869
      //
 
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.
 
2877
      //
 
2878
 
 
2879
      var list = _source.Select(new Func<T, int, Tuple<T, int>>(TagPosition)).ToList();
 
2880
 
 
2881
      list.Sort((x, y) =>
 
2882
        {
 
2883
          //
 
2884
          // Compare keys from left to right.
 
2885
          //
 
2886
 
 
2887
          var comparisons = _comparisons;
 
2888
          for (var i = 0; i < comparisons.Count; i++)
 
2889
          {
 
2890
            var result = comparisons[i](x.First, y.First);
 
2891
            if (result != 0)
 
2892
              return result;
 
2893
          }
 
2894
 
 
2895
          //
 
2896
          // All keys compared equal so now break the tie by their
 
2897
          // position in the original sequence, making the sort stable.
 
2898
          //
 
2899
 
 
2900
          return x.Second.CompareTo(y.Second);
 
2901
        });
 
2902
 
 
2903
      return list.Select(new Func<Tuple<T, int>, T>(GetFirst)).GetEnumerator();
 
2904
 
 
2905
    }
 
2906
 
 
2907
    /// <remarks>
 
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.
 
2911
    /// </remarks>
 
2912
 
 
2913
    private static Tuple<T, int> TagPosition(T e, int i)
 
2914
    {
 
2915
      return new Tuple<T, int>(e, i);
 
2916
    }
 
2917
 
 
2918
    /// <remarks>
 
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.
 
2922
    /// </remarks>
 
2923
 
 
2924
    private static T GetFirst(Tuple<T, int> pv)
 
2925
    {
 
2926
      return pv.First;
 
2927
    }
 
2928
 
 
2929
    IEnumerator IEnumerable.GetEnumerator()
 
2930
    {
 
2931
      return GetEnumerator();
 
2932
    }
 
2933
  }
 
2934
 
 
2935
  [Serializable]
 
2936
  internal struct Tuple<TFirst, TSecond> : IEquatable<Tuple<TFirst, TSecond>>
 
2937
  {
 
2938
    public TFirst First { get; private set; }
 
2939
    public TSecond Second { get; private set; }
 
2940
 
 
2941
    public Tuple(TFirst first, TSecond second)
 
2942
      : this()
 
2943
    {
 
2944
      First = first;
 
2945
      Second = second;
 
2946
    }
 
2947
 
 
2948
    public override bool Equals(object obj)
 
2949
    {
 
2950
      return obj != null
 
2951
             && obj is Tuple<TFirst, TSecond>
 
2952
             && base.Equals((Tuple<TFirst, TSecond>) obj);
 
2953
    }
 
2954
 
 
2955
    public bool Equals(Tuple<TFirst, TSecond> other)
 
2956
    {
 
2957
      return EqualityComparer<TFirst>.Default.Equals(other.First, First)
 
2958
             && EqualityComparer<TSecond>.Default.Equals(other.Second, Second);
 
2959
    }
 
2960
 
 
2961
    public override int GetHashCode()
 
2962
    {
 
2963
      var num = 0x7a2f0b42;
 
2964
      num = (-1521134295*num) + EqualityComparer<TFirst>.Default.GetHashCode(First);
 
2965
      return (-1521134295*num) + EqualityComparer<TSecond>.Default.GetHashCode(Second);
 
2966
    }
 
2967
 
 
2968
    public override string ToString()
 
2969
    {
 
2970
      return string.Format(CultureInfo.InvariantCulture, @"{{ First = {0}, Second = {1} }}", First, Second);
 
2971
    }
 
2972
  }
 
2973
}
 
2974
 
 
2975
namespace Newtonsoft.Json.Serialization
 
2976
{
 
2977
  public delegate TResult Func<TResult>();
 
2978
 
 
2979
  public delegate TResult Func<T, TResult>(T a);
 
2980
 
 
2981
  public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
 
2982
 
 
2983
  public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
 
2984
 
 
2985
  public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 
2986
 
 
2987
  public delegate void Action();
 
2988
 
 
2989
  public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
 
2990
 
 
2991
  public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
 
2992
 
 
2993
  public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 
2994
}
 
2995
 
 
2996
namespace System.Runtime.CompilerServices
 
2997
{
 
2998
  /// <remarks>
 
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>.
 
3005
  /// </remarks>
 
3006
 
 
3007
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
 
3008
  internal sealed class ExtensionAttribute : Attribute { }
 
3009
}
 
3010
 
 
3011
#endif
 
 
b'\\ No newline at end of file'