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