2009-03-28 Jb Evain <jbevain@novell.com>
[mono.git] / mcs / class / System.Core / System.Linq / Enumerable.cs
index 64d03332672dced6da31f4b9e57bdb258e1a6cdf..d2c98d0a1954f16a877a18c2c856d759747d2563 100644 (file)
@@ -1,3 +1,14 @@
+//
+// Enumerable.cs
+//
+// Authors:
+//  Marek Safar (marek.safar@gmail.com)
+//  Antonello Provenzano  <antonello@deveel.com>
+//  Alejandro Serrano "Serras" (trupill@yahoo.es)
+//  Jb Evain (jbevain@novell.com)
+//
+// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
+//
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 // "Software"), to deal in the Software without restriction, including
 // distribute, sublicense, and/or sell copies of the Software, and to
 // permit persons to whom the Software is furnished to do so, subject to
 // the following conditions:
-// 
+//
 // The above copyright notice and this permission notice shall be
 // included in all copies or substantial portions of the Software.
-// 
+//
 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-// Authors:
-//        Marek Safar (marek.safar@gmail.com)
-//        Antonello Provenzano  <antonello@deveel.com>
-//        Alejandro Serrano "Serras" (trupill@yahoo.es)
-//
+
+// precious: http://www.hookedonlinq.com
 
 using System;
 using System.Collections;
@@ -31,17 +40,28 @@ namespace System.Linq
 {
        public static class Enumerable
        {
+               enum Fallback {
+                       Default,
+                       Throw
+               }
+
+               class PredicateOf<T> {
+                       public static readonly Func<T, bool> Always = (t) => true;
+               }
+
+               class Function<T> {
+                       public static readonly Func<T, T> Identity = (t) => t;
+               }
+
                #region Aggregate
+
                public static TSource Aggregate<TSource> (this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
-                       if (func == null)
-                               throw new ArgumentNullException ("func");
+                       Check.SourceAndFunc (source, func);
 
-                       // custom foreach so that we can efficiently throw an exception 
+                       // custom foreach so that we can efficiently throw an exception
                        // if zero elements and treat the first element differently
-                       using (IEnumerator<TSource> enumerator = source.GetEnumerator ()) {
+                       using (var enumerator = source.GetEnumerator ()) {
                                if (!enumerator.MoveNext ())
                                        throw new InvalidOperationException ("No elements in source list");
 
@@ -52,406 +72,291 @@ namespace System.Linq
                        }
                }
 
-
                public static TAccumulate Aggregate<TSource, TAccumulate> (this IEnumerable<TSource> source,
                        TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
                {
-                       if (source == null || func == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndFunc (source, func);
 
                        TAccumulate folded = seed;
                        foreach (TSource element in source)
                                folded = func (folded, element);
+
                        return folded;
                }
 
-
                public static TResult Aggregate<TSource, TAccumulate, TResult> (this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
-                       if (func == null)
-                               throw new ArgumentNullException ("func");
+                       Check.SourceAndFunc (source, func);
                        if (resultSelector == null)
                                throw new ArgumentNullException ("resultSelector");
 
-                       TAccumulate result = seed;
-                       foreach (TSource e in source)
+                       var result = seed;
+                       foreach (var e in source)
                                result = func (result, e);
+
                        return resultSelector (result);
                }
+
                #endregion
 
                #region All
+
                public static bool All<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
-                       foreach (TSource element in source)
+                       foreach (var element in source)
                                if (!predicate (element))
                                        return false;
+
                        return true;
                }
+
                #endregion
 
                #region Any
+
                public static bool Any<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       foreach (TSource element in source)
-                               return true;
-                       return false;
-               }
+                       var collection = source as ICollection<TSource>;
+                       if (collection != null)
+                               return collection.Count > 0;
 
+                       using (var enumerator = source.GetEnumerator ())
+                               return enumerator.MoveNext ();
+               }
 
                public static bool Any<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
                        foreach (TSource element in source)
                                if (predicate (element))
                                        return true;
+
                        return false;
                }
+
                #endregion
 
                #region AsEnumerable
+
                public static IEnumerable<TSource> AsEnumerable<TSource> (this IEnumerable<TSource> source)
                {
                        return source;
                }
+
                #endregion
 
                #region Average
+
                public static double Average (this IEnumerable<int> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (int element in source) {
-                               sum += element;
-                               counter++;
-                       }
-
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return (double) sum / (double) counter;
+                       return Average<int, long, double> (source, (a, b) => a + b, (a, b) => (double) a / (double) b);
                }
 
+               public static double Average (this IEnumerable<long> source)
+               {
+                       return Average<long, long, double> (source, (a, b) => a + b, (a, b) => (double) a / (double) b);
+               }
 
-               public static double? Average (this IEnumerable<int?> source)
+               public static double Average (this IEnumerable<double> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       return Average<double, double, double> (source, (a, b) => a + b, (a, b) => a / b);
+               }
 
-                       bool onlyNull = true;
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (int? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) sum / (double?) counter);
+               public static float Average (this IEnumerable<float> source)
+               {
+                       return Average<float, double, float> (source, (a, b) => a + b, (a, b) => (float) a / (float) b);
                }
 
+               public static decimal Average (this IEnumerable<decimal> source)
+               {
+                       return Average<decimal, decimal, decimal> (source, (a, b) => a + b, (a, b) => a / b);
+               }
 
-               public static double Average (this IEnumerable<long> source)
+               static TResult Average<TElement, TAggregate, TResult> (this IEnumerable<TElement> source,
+                       Func<TAggregate, TElement, TAggregate> func, Func<TAggregate, long, TResult> result)
+                       where TElement : struct
+                       where TAggregate : struct
+                       where TResult : struct
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       long sum = 0;
+                       var total = default (TAggregate);
                        long counter = 0;
-                       foreach (long element in source) {
-                               sum += element;
-                               counter++;
+                       foreach (var element in source) {
+                               total = func (total, element);
+                               ++counter;
                        }
 
                        if (counter == 0)
                                throw new InvalidOperationException ();
-                       else
-                               return (double) sum / (double) counter;
-               }
 
+                       return result (total, counter);
+               }
 
-               public static double? Average (this IEnumerable<long?> source)
+               static TResult? AverageNullable<TElement, TAggregate, TResult> (this IEnumerable<TElement?> source,
+                       Func<TAggregate, TElement, TAggregate> func, Func<TAggregate, long, TResult> result)
+                       where TElement : struct
+                       where TAggregate : struct
+                       where TResult : struct
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       bool onlyNull = true;
-                       long sum = 0;
+                       var total = default (TAggregate);
                        long counter = 0;
-                       foreach (long? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) sum / (double?) counter);
-               }
-
-
-               public static double Average (this IEnumerable<double> source)
-               {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
 
-                       double sum = 0;
-                       double counter = 0;
-                       foreach (double element in source) {
-                               sum += element;
+                               total = func (total, element.Value);
                                counter++;
                        }
 
                        if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return sum / counter;
-               }
+                               return null;
 
+                       return new TResult? (result (total, counter));
+               }
 
-               public static double? Average (this IEnumerable<double?> source)
+               public static double? Average (this IEnumerable<int?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       double sum = 0;
-                       double counter = 0;
-                       foreach (double? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) (sum / counter));
-               }
+                       Check.Source (source);
 
+                       return source.AverageNullable<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+               }
 
-               public static decimal Average (this IEnumerable<decimal> source)
+               public static double? Average (this IEnumerable<long?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       decimal sum = 0;
-                       decimal counter = 0;
-                       foreach (decimal element in source) {
-                               sum += element;
-                               counter++;
-                       }
+                       Check.Source (source);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return sum / counter;
+                       return source.AverageNullable<long, long, double> ((a, b) => a + b, (a, b) => (double) a / b);
                }
 
+               public static double? Average (this IEnumerable<double?> source)
+               {
+                       Check.Source (source);
+
+                       return source.AverageNullable<double, double, double> ((a, b) => a + b, (a, b) => a / b);
+               }
 
                public static decimal? Average (this IEnumerable<decimal?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       decimal sum = 0;
-                       decimal counter = 0;
-                       foreach (decimal? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (decimal?) (sum / counter));
+                       Check.Source (source);
+
+                       return source.AverageNullable<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
                }
 
+               public static float? Average (this IEnumerable<float?> source)
+               {
+                       Check.Source (source);
+
+                       return source.AverageNullable<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
+               }
 
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (TSource item in source) {
-                               sum += selector (item);
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return (double) sum / (double) counter;
+                       return source.Select (selector).Average<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
                }
 
-
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (TSource item in source) {
-                               int? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) sum / (double?) counter);
+                       return source.Select (selector).AverageNullable<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
                }
 
-
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (TSource item in source) {
-                               sum += selector (item);
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return (double) sum / (double) counter;
+                       return source.Select (selector).Average<long, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
                }
 
-
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       long sum = 0;
-                       long counter = 0;
-                       foreach (TSource item in source) {
-                               long? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) sum / (double?) counter);
+                       return source.Select (selector).AverageNullable<long, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
                }
 
-
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       double sum = 0;
-                       double counter = 0;
-                       foreach (TSource item in source) {
-                               sum += selector (item);
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return sum / counter;
+                       return source.Select (selector).Average<double, double, double> ((a, b) => a + b, (a, b) => a / b);
                }
 
-
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       double sum = 0;
-                       double counter = 0;
-                       foreach (TSource item in source) {
-                               double? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (double?) (sum / counter));
+                       return source.Select (selector).AverageNullable<double, double, double> ((a, b) => a + b, (a, b) => a / b);
                }
 
-
-               public static decimal Average<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
+               public static float Average<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       decimal sum = 0;
-                       decimal counter = 0;
-                       foreach (TSource item in source) {
-                               sum += selector (item);
-                               counter++;
-                       }
+                       return source.Select (selector).Average<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
+               }
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return sum / counter;
+               public static float? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return source.Select (selector).AverageNullable<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
                }
 
+               public static decimal Average<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return source.Select (selector).Average<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
+               }
 
                public static decimal? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       decimal sum = 0;
-                       decimal counter = 0;
-                       foreach (TSource item in source) {
-                               decimal? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       sum += element.Value;
-                                       counter++;
-                               }
-                       }
-                       return (onlyNull ? null : (decimal?) (sum / counter));
+                       return source.Select (selector).AverageNullable<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
                }
+
                #endregion
 
                #region Cast
+
                public static IEnumerable<TResult> Cast<TResult> (this IEnumerable source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       foreach (object element in source)
-                               yield return (TResult) element;
+                       return CreateCastIterator<TResult> (source);
+               }
+
+               static IEnumerable<TResult> CreateCastIterator<TResult> (IEnumerable source)
+               {
+                       foreach (TResult element in source)
+                               yield return element;
                }
+
                #endregion
 
                #region Concat
+
                public static IEnumerable<TSource> Concat<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second)
                {
-                       if (first == null || second == null)
-                               throw new ArgumentNullException ();
+                       Check.FirstAndSecond (first, second);
+
+                       return CreateConcatIterator (first, second);
+               }
 
+               static IEnumerable<TSource> CreateConcatIterator<TSource> (IEnumerable<TSource> first, IEnumerable<TSource> second)
+               {
                        foreach (TSource element in first)
                                yield return element;
                        foreach (TSource element in second)
@@ -464,59 +369,58 @@ namespace System.Linq
 
                public static bool Contains<TSource> (this IEnumerable<TSource> source, TSource value)
                {
-                       ICollection<TSource> collection = source as ICollection<TSource>;
+                       var collection = source as ICollection<TSource>;
                        if (collection != null)
                                return collection.Contains (value);
 
                        return Contains<TSource> (source, value, null);
                }
 
-
                public static bool Contains<TSource> (this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
+                       Check.Source (source);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TSource>.Default;
 
-                       foreach (TSource e in source) {
-                               if (comparer.Equals (e, value))
+                       foreach (var element in source)
+                               if (comparer.Equals (element, value))
                                        return true;
-                       }
 
                        return false;
                }
                #endregion
 
                #region Count
+
                public static int Count<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       ICollection<TSource> collection = source as ICollection<TSource>;
+                       var collection = source as ICollection<TSource>;
                        if (collection != null)
                                return collection.Count;
 
                        int counter = 0;
-                       foreach (TSource element in source)
-                               counter++;
+                       using (var enumerator = source.GetEnumerator ())
+                               while (enumerator.MoveNext ())
+                                       counter++;
+
                        return counter;
                }
 
                public static int Count<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
                        int counter = 0;
-                       foreach (TSource element in source)
+                       foreach (var element in source)
                                if (selector (element))
                                        counter++;
 
                        return counter;
                }
+
                #endregion
 
                #region DefaultIfEmpty
@@ -528,16 +432,20 @@ namespace System.Linq
 
                public static IEnumerable<TSource> DefaultIfEmpty<TSource> (this IEnumerable<TSource> source, TSource defaultValue)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
+                       Check.Source (source);
+
+                       return CreateDefaultIfEmptyIterator (source, defaultValue);
+               }
 
-                       bool noYield = true;
+               static IEnumerable<TSource> CreateDefaultIfEmptyIterator<TSource> (IEnumerable<TSource> source, TSource defaultValue)
+               {
+                       bool empty = true;
                        foreach (TSource item in source) {
-                               noYield = false;
+                               empty = false;
                                yield return item;
                        }
 
-                       if (noYield)
+                       if (empty)
                                yield return defaultValue;
                }
 
@@ -552,43 +460,56 @@ namespace System.Linq
 
                public static IEnumerable<TSource> Distinct<TSource> (this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TSource>.Default;
 
-                       List<TSource> items = new List<TSource> (); // TODO: use a HashSet here
-                       foreach (TSource element in source) {
-                               if (!Contains (items, element, comparer)) {
+                       return CreateDistinctIterator (source, comparer);
+               }
+
+               static IEnumerable<TSource> CreateDistinctIterator<TSource> (IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
+               {
+                       var items = new HashSet<TSource> (comparer);
+                       foreach (var element in source) {
+                               if (! items.Contains (element)) {
                                        items.Add (element);
                                        yield return element;
                                }
                        }
                }
+
                #endregion
 
                #region ElementAt
 
+               static TSource ElementAt<TSource> (this IEnumerable<TSource> source, int index, Fallback fallback)
+               {
+                       long counter = 0L;
+
+                       foreach (var element in source) {
+                               if (index == counter++)
+                                       return element;
+                       }
+
+                       if (fallback == Fallback.Throw)
+                               throw new ArgumentOutOfRangeException ();
+
+                       return default (TSource);
+               }
+
                public static TSource ElementAt<TSource> (this IEnumerable<TSource> source, int index)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
+
                        if (index < 0)
                                throw new ArgumentOutOfRangeException ();
 
-                       IList<TSource> list = source as IList<TSource>;
+                       var list = source as IList<TSource>;
                        if (list != null)
                                return list [index];
 
-                       int counter = 0;
-                       foreach (TSource element in source) {
-                               if (counter == index)
-                                       return element;
-                               counter++;
-                       }
-
-                       throw new ArgumentOutOfRangeException ();
+                       return source.ElementAt (index, Fallback.Throw);
                }
 
                #endregion
@@ -597,32 +518,27 @@ namespace System.Linq
 
                public static TSource ElementAtOrDefault<TSource> (this IEnumerable<TSource> source, int index)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
+
                        if (index < 0)
                                return default (TSource);
 
-                       IList<TSource> list = source as IList<TSource>;
+                       var list = source as IList<TSource>;
                        if (list != null)
                                return index < list.Count ? list [index] : default (TSource);
 
-                       int counter = 0;
-                       foreach (TSource element in source) {
-                               if (counter == index)
-                                       return element;
-                               counter++;
-                       }
-
-                       return default (TSource);
+                       return source.ElementAt (index, Fallback.Default);
                }
 
                #endregion
 
                #region Empty
+
                public static IEnumerable<TResult> Empty<TResult> ()
                {
-                       return new List<TResult> ();
+                       return new TResult [0];
                }
+
                #endregion
 
                #region Except
@@ -634,15 +550,19 @@ namespace System.Linq
 
                public static IEnumerable<TSource> Except<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
                {
-                       if (first == null || second == null)
-                               throw new ArgumentNullException ();
+                       Check.FirstAndSecond (first, second);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TSource>.Default;
 
-                       List<TSource> items = new List<TSource> (Distinct (second));
-                       foreach (TSource element in first) {
-                               if (!Contains (items, element, comparer))
+                       return CreateExceptIterator (first, second, comparer);
+               }
+
+               static IEnumerable<TSource> CreateExceptIterator<TSource> (IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
+               {
+                       var items = new HashSet<TSource> (second, comparer);
+                       foreach (var element in first) {
+                               if (!items.Contains (element, comparer))
                                        yield return element;
                        }
                }
@@ -651,58 +571,61 @@ namespace System.Linq
 
                #region First
 
-               public static TSource First<TSource> (this IEnumerable<TSource> source)
+               static TSource First<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate, Fallback fallback)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       foreach (var element in source)
+                               if (predicate (element))
+                                       return element;
 
-                       foreach (TSource element in source)
-                               return element;
+                       if (fallback == Fallback.Throw)
+                               throw new InvalidOperationException ();
 
-                       throw new InvalidOperationException ();
+                       return default (TSource);
                }
 
-
-               public static TSource First<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               public static TSource First<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       foreach (TSource element in source) {
-                               if (predicate (element))
-                                       return element;
+                       var list = source as IList<TSource>;
+                       if (list != null) {
+                               if (list.Count != 0)
+                                       return list [0];
+
+                               throw new InvalidOperationException ();
+                       } else {
+                               using (var enumerator = source.GetEnumerator ()) {
+                                       if (enumerator.MoveNext ())
+                                               return enumerator.Current;
+                               }
                        }
 
                        throw new InvalidOperationException ();
                }
 
+               public static TSource First<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return source.First (predicate, Fallback.Throw);
+               }
+
                #endregion
 
                #region FirstOrDefault
 
                public static TSource FirstOrDefault<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       foreach (TSource element in source)
-                               return element;
-
-                       return default (TSource);
+                       return source.First (PredicateOf<TSource>.Always, Fallback.Default);
                }
 
-
                public static TSource FirstOrDefault<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
-                       foreach (TSource element in source) {
-                               if (predicate (element))
-                                       return element;
-                       }
-
-                       return default (TSource);
+                       return source.First (predicate, Fallback.Default);
                }
 
                #endregion
@@ -720,20 +643,23 @@ namespace System.Linq
                        return null;
                }
 
-
                public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector)
                {
                        return GroupBy<TSource, TKey> (source, keySelector, null);
                }
 
-
                public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeySelector (source, keySelector);
+
+                       return CreateGroupByIterator (source, keySelector, comparer);
+               }
 
+               static IEnumerable<IGrouping<TKey, TSource>> CreateGroupByIterator<TSource, TKey> (this IEnumerable<TSource> source,
+                       Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
+               {
                        Dictionary<TKey, List<TSource>> groups = new Dictionary<TKey, List<TSource>> ();
                        List<TSource> nullList = new List<TSource> ();
                        int counter = 0;
@@ -771,19 +697,16 @@ namespace System.Linq
                        }
                }
 
-
                public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
                {
                        return GroupBy<TSource, TKey, TElement> (source, keySelector, elementSelector, null);
                }
 
-
                public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null || elementSelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeyElementSelectors (source, keySelector, elementSelector);
 
                        Dictionary<TKey, List<TElement>> groups = new Dictionary<TKey, List<TElement>> ();
                        List<TElement> nullList = new List<TElement> ();
@@ -823,6 +746,43 @@ namespace System.Linq
                        }
                }
 
+               public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult> (this IEnumerable<TSource> source,
+                       Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector,
+                       Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
+               {
+                       return GroupBy (source, keySelector, elementSelector, resultSelector, null);
+               }
+
+               public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult> (this IEnumerable<TSource> source,
+                       Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector,
+                       Func<TKey, IEnumerable<TElement>, TResult> resultSelector,
+                       IEqualityComparer<TKey> comparer)
+               {
+                       IEnumerable<IGrouping<TKey, TElement>> groups = GroupBy<TSource, TKey, TElement> (
+                               source, keySelector, elementSelector, comparer);
+
+                       foreach (IGrouping<TKey, TElement> group in groups)
+                               yield return resultSelector (group.Key, group);
+               }
+
+               public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult> (this IEnumerable<TSource> source,
+                       Func<TSource, TKey> keySelector,
+                       Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
+               {
+                       return GroupBy (source, keySelector, resultSelector, null);
+               }
+
+               public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult> (this IEnumerable<TSource> source,
+                       Func<TSource, TKey> keySelector,
+                       Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
+                       IEqualityComparer<TKey> comparer)
+               {
+                       IEnumerable<IGrouping<TKey,TSource>> groups = GroupBy<TSource, TKey> (source, keySelector, comparer);
+
+                       foreach (IGrouping<TKey, TSource> group in groups)
+                               yield return resultSelector (group.Key, group);
+               }
+
                #endregion
 
                # region GroupJoin
@@ -839,14 +799,20 @@ namespace System.Linq
                        Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
                        IEqualityComparer<TKey> comparer)
                {
-                       if (outer == null || inner == null || outerKeySelector == null ||
-                               innerKeySelector == null || resultSelector == null)
-                               throw new ArgumentNullException ();
+                       Check.JoinSelectors (outer, inner, outerKeySelector, innerKeySelector, resultSelector);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TKey>.Default;
 
-                       Lookup<TKey, TInner> innerKeys = ToLookup<TInner, TKey> (inner, innerKeySelector, comparer);
+                       return CreateGroupJoinIterator (outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer);
+               }
+
+               static IEnumerable<TResult> CreateGroupJoinIterator<TOuter, TInner, TKey, TResult> (this IEnumerable<TOuter> outer,
+                       IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
+                       Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
+                       IEqualityComparer<TKey> comparer)
+               {
+                       ILookup<TKey, TInner> innerKeys = ToLookup<TInner, TKey> (inner, innerKeySelector, comparer);
                        /*Dictionary<K, List<U>> innerKeys = new Dictionary<K, List<U>> ();
                        foreach (U element in inner)
                        {
@@ -862,7 +828,7 @@ namespace System.Linq
                                        yield return resultSelector (element, innerKeys [outerKey]);
                                else
                                        yield return resultSelector (element, Empty<TInner> ());
-                       }       
+                       }
                }
 
                #endregion
@@ -876,15 +842,19 @@ namespace System.Linq
 
                public static IEnumerable<TSource> Intersect<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
                {
-                       if (first == null || second == null)
-                               throw new ArgumentNullException ();
+                       Check.FirstAndSecond (first, second);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TSource>.Default;
 
-                       List<TSource> items = new List<TSource> (Distinct (first));
-                       foreach (TSource element in second) {
-                               if (Contains (items, element, comparer))
+                       return CreateIntersectIterator (first, second, comparer);
+               }
+
+               static IEnumerable<TSource> CreateIntersectIterator<TSource> (IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
+               {
+                       var items = new HashSet<TSource> (second, comparer);
+                       foreach (TSource element in first) {
+                               if (items.Remove (element))
                                        yield return element;
                        }
                }
@@ -897,14 +867,19 @@ namespace System.Linq
                        IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
                        Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
                {
-                       if (outer == null || inner == null || outerKeySelector == null ||
-                                       innerKeySelector == null || resultSelector == null)
-                               throw new ArgumentNullException ();
+                       Check.JoinSelectors (outer, inner, outerKeySelector, innerKeySelector, resultSelector);
 
                        if (comparer == null)
                                comparer = EqualityComparer<TKey>.Default;
 
-                       Lookup<TKey, TInner> innerKeys = ToLookup<TInner, TKey> (inner, innerKeySelector, comparer);
+                       return CreateJoinIterator (outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer);
+               }
+
+               static IEnumerable<TResult> CreateJoinIterator<TOuter, TInner, TKey, TResult> (this IEnumerable<TOuter> outer,
+                       IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
+                       Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
+               {
+                       ILookup<TKey, TInner> innerKeys = ToLookup<TInner, TKey> (inner, innerKeySelector, comparer);
                        /*Dictionary<K, List<U>> innerKeys = new Dictionary<K, List<U>> ();
                        foreach (U element in inner)
                        {
@@ -927,49 +902,55 @@ namespace System.Linq
                        IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
                        Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
                {
-                       return Join<TOuter, TInner, TKey, TResult> (outer, inner, outerKeySelector, innerKeySelector, resultSelector, null);
+                       return outer.Join (inner, outerKeySelector, innerKeySelector, resultSelector, null);
                }
-               # endregion
+
+               #endregion
 
                #region Last
 
-               public static TSource Last<TSource> (this IEnumerable<TSource> source)
+               static TSource Last<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate, Fallback fallback)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       var empty = true;
+                       var item = default (TSource);
 
-                       bool noElements = true;
-                       TSource lastElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (noElements) noElements = false;
-                               lastElement = element;
+                       foreach (var element in source) {
+                               if (!predicate (element))
+                                       continue;
+
+                               item = element;
+                               empty = false;
                        }
 
-                       if (!noElements)
-                               return lastElement;
-                       else
+                       if (!empty)
+                               return item;
+
+                       if (fallback == Fallback.Throw)
                                throw new InvalidOperationException ();
+
+                       return item;
                }
 
-               public static TSource Last<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, bool> predicate)
+               public static TSource Last<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
-
-                       bool noElements = true;
-                       TSource lastElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (predicate (element)) {
-                                       if (noElements) noElements = false;
-                                       lastElement = element;
-                               }
-                       }
+                       Check.Source (source);
 
-                       if (!noElements)
-                               return lastElement;
-                       else
+                       var collection = source as ICollection<TSource>;
+                       if (collection != null && collection.Count == 0)
                                throw new InvalidOperationException ();
+
+                       var list = source as IList<TSource>;
+                       if (list != null)
+                               return list [list.Count - 1];
+
+                       return source.Last (PredicateOf<TSource>.Always, Fallback.Throw);
+               }
+
+               public static TSource Last<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return source.Last (predicate, Fallback.Throw);
                }
 
                #endregion
@@ -978,50 +959,47 @@ namespace System.Linq
 
                public static TSource LastOrDefault<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       TSource lastElement = default (TSource);
-                       foreach (TSource element in source)
-                               lastElement = element;
+                       var list = source as IList<TSource>;
+                       if (list != null)
+                               return list.Count > 0 ? list [list.Count - 1] : default (TSource);
 
-                       return lastElement;
+                       return source.Last (PredicateOf<TSource>.Always, Fallback.Default);
                }
 
-               public static TSource LastOrDefault<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, bool> predicate)
+               public static TSource LastOrDefault<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
-
-                       TSource lastElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (predicate (element))
-                                       lastElement = element;
-                       }
+                       Check.SourceAndPredicate (source, predicate);
 
-                       return lastElement;
+                       return source.Last (predicate, Fallback.Default);
                }
 
                #endregion
 
                #region LongCount
+
                public static long LongCount<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
+
+#if !NET_2_1
+                       var array = source as TSource [];
+                       if (array != null)
+                               return array.LongLength;
+#endif
 
                        long counter = 0;
-                       foreach (TSource element in source)
-                               counter++;
+                       using (var enumerator = source.GetEnumerator ())
+                               while (enumerator.MoveNext ())
+                                       counter++;
+
                        return counter;
                }
 
-
                public static long LongCount<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
                        long counter = 0;
                        foreach (TSource element in source)
@@ -1037,160 +1015,123 @@ namespace System.Linq
 
                public static int Max (this IEnumerable<int> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       int maximum = int.MinValue;
-                       int counter = 0;
-                       foreach (int element in source) {
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       Check.Source (source);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+                       return Iterate (source, int.MinValue, (a, b) => Math.Max (a, b));
                }
 
-
-               public static int? Max (this IEnumerable<int?> source)
+               public static long Max (this IEnumerable<long> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       int? maximum = int.MinValue;
-                       foreach (int? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       Check.Source (source);
+
+                       return Iterate (source, long.MinValue, (a, b) => Math.Max (a, b));
                }
 
+               public static double Max (this IEnumerable<double> source)
+               {
+                       Check.Source (source);
 
-               public static long Max (this IEnumerable<long> source)
+                       return Iterate (source, double.MinValue, (a, b) => Math.Max (a, b));
+               }
+
+               public static float Max (this IEnumerable<float> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       long maximum = long.MinValue;
-                       int counter = 0;
-                       foreach (long element in source) {
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       return Iterate (source, float.MinValue, (a, b) => Math.Max (a, b));
+               }
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+               public static decimal Max (this IEnumerable<decimal> source)
+               {
+                       Check.Source (source);
+
+                       return Iterate (source, decimal.MinValue, (a, b) => Math.Max (a, b));
                }
 
+               public static int? Max (this IEnumerable<int?> source)
+               {
+                       Check.Source (source);
+
+                       return IterateNullable (source, (a, b) => Math.Max (a, b));
+               }
 
                public static long? Max (this IEnumerable<long?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       long? maximum = long.MinValue;
-                       foreach (long? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
-               }
+                       Check.Source (source);
 
+                       return IterateNullable (source, (a, b) => Math.Max (a, b));
+               }
 
-               public static double Max (this IEnumerable<double> source)
+               public static double? Max (this IEnumerable<double?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       double maximum = double.MinValue;
-                       int counter = 0;
-                       foreach (double element in source) {
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       Check.Source (source);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+                       return IterateNullable (source, (a, b) => Math.Max (a, b));
                }
 
-
-               public static double? Max (this IEnumerable<double?> source)
+               public static float? Max (this IEnumerable<float?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       double? maximum = double.MinValue;
-                       foreach (double? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       Check.Source (source);
+
+                       return IterateNullable (source, (a, b) => Math.Max (a, b));
                }
 
+               public static decimal? Max (this IEnumerable<decimal?> source)
+               {
+                       Check.Source (source);
+
+                       return IterateNullable (source, (a, b) => Math.Max (a, b));
+               }
 
-               public static decimal Max (this IEnumerable<decimal> source)
+               static T? IterateNullable<T> (IEnumerable<T?> source, Func<T, T, T> selector) where T : struct
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       bool empty = true;
+                       T? value = null;
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
 
-                       decimal maximum = decimal.MinValue;
-                       int counter = 0;
-                       foreach (decimal element in source) {
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
+                               if (!value.HasValue)
+                                       value = element.Value;
+                               else
+                                       value = selector (element.Value, value.Value);
+
+                               empty = false;
                        }
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
-               }
+                       if (empty)
+                               return null;
 
+                       return value;
+               }
 
-               public static decimal? Max (this IEnumerable<decimal?> source)
+               static TRet? IterateNullable<TSource, TRet> (
+                       IEnumerable<TSource> source,
+                       Func<TSource, TRet?> source_selector,
+                       Func<TRet?, TRet?, bool> selector) where TRet : struct
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       decimal? maximum = decimal.MinValue;
-                       foreach (decimal? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
+                       bool empty = true;
+                       TRet? value = null;
+                       foreach (var element in source) {
+                               TRet? item = source_selector (element);
+
+                               if (!value.HasValue)
+                                       value = item;
+                               else if (selector (item, value))
+                                       value = item;
+
+                               empty = false;
                        }
-                       return (onlyNull ? null : maximum);
-               }
 
+                       if (empty)
+                               return null;
+
+                       return value;
+               }
 
                public static TSource Max<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
                        bool notAssigned = true;
                        TSource maximum = default (TSource);
@@ -1220,180 +1161,93 @@ namespace System.Linq
                                return maximum;
                }
 
-
-               public static int Max<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, int> selector)
+               public static int Max<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       int maximum = int.MinValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               int element = selector (item);
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+                       return Iterate (source, int.MinValue, (a, b) => Math.Max (selector (a), b));
                }
 
-
-               public static int? Max<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, int?> selector)
+               public static long Max<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       int? maximum = int.MinValue;
-                       foreach (TSource item in source) {
-                               int? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       return Iterate (source, long.MinValue, (a, b) => Math.Max (selector (a), b));
                }
 
-
-               public static long Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, long> selector)
+               public static double Max<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       long maximum = long.MinValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               long element = selector (item);
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+                       return Iterate (source, double.MinValue, (a, b) => Math.Max (selector (a), b));
                }
 
-
-               public static long? Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, long?> selector)
+               public static float Max<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       long? maximum = long.MinValue;
-                       foreach (TSource item in source) {
-                               long? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       return Iterate (source, float.MinValue, (a, b) => Math.Max (selector (a), b));
                }
 
-
-               public static double Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, double> selector)
+               public static decimal Max<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       double maximum = double.MinValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               double element = selector (item);
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
+                       return Iterate (source, decimal.MinValue, (a, b) => Math.Max (selector (a), b));
+               }
+
+               static U Iterate<T, U> (IEnumerable<T> source, U initValue, Func<T, U, U> selector)
+               {
+                       bool empty = true;
+                       foreach (var element in source) {
+                               initValue = selector (element, initValue);
+                               empty = false;
                        }
 
-                       if (counter == 0)
+                       if (empty)
                                throw new InvalidOperationException ();
-                       else
-                               return maximum;
-               }
 
+                       return initValue;
+               }
 
-               public static double? Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, double?> selector)
+               public static int? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       double? maximum = double.MinValue;
-                       foreach (TSource item in source) {
-                               double? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       return IterateNullable (source, selector, (a, b) => a > b);
                }
 
-
-               public static decimal Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, decimal> selector)
+               public static long? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       decimal maximum = decimal.MinValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               decimal element = selector (item);
-                               if (element > maximum)
-                                       maximum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return maximum;
+                       return IterateNullable (source, selector, (a, b) => a > b);
                }
 
+               public static double? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
 
-               public static decimal? Max<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, decimal?> selector)
+                       return IterateNullable (source, selector, (a, b) => a > b);
+               }
+
+               public static float? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       decimal? maximum = decimal.MinValue;
-                       foreach (TSource item in source) {
-                               decimal? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element > maximum)
-                                               maximum = element;
-                               }
-                       }
-                       return (onlyNull ? null : maximum);
+                       return IterateNullable (source, selector, (a, b) => a > b);
                }
 
+               public static decimal? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
 
-               public static TResult Max<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, TResult> selector)
+                       return IterateNullable (source, selector, (a, b) => a > b);
+               }
+
+               public static TResult Max<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
                        bool notAssigned = true;
                        TResult maximum = default (TResult);
@@ -1430,159 +1284,77 @@ namespace System.Linq
 
                public static int Min (this IEnumerable<int> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       int minimum = int.MaxValue;
-                       int counter = 0;
-                       foreach (int element in source) {
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.Source (source);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return Iterate (source, int.MaxValue, (a, b) => Math.Min (a, b));
                }
 
-
-               public static int? Min (this IEnumerable<int?> source)
+               public static long Min (this IEnumerable<long> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       int? minimum = int.MaxValue;
-                       foreach (int? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
+                       Check.Source (source);
+
+                       return Iterate (source, long.MaxValue, (a, b) => Math.Min (a, b));
                }
 
-               public static long Min (this IEnumerable<long> source)
+               public static double Min (this IEnumerable<double> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       long minimum = long.MaxValue;
-                       int counter = 0;
-                       foreach (long element in source) {
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.Source (source);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return Iterate (source, double.MaxValue, (a, b) => Math.Min (a, b));
                }
 
-
-               public static long? Min (this IEnumerable<long?> source)
+               public static float Min (this IEnumerable<float> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       long? minimum = long.MaxValue;
-                       foreach (long? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
-               }
+                       Check.Source (source);
 
+                       return Iterate (source, float.MaxValue, (a, b) => Math.Min (a, b));
+               }
 
-               public static double Min (this IEnumerable<double> source)
+               public static decimal Min (this IEnumerable<decimal> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       double minimum = double.MaxValue;
-                       int counter = 0;
-                       foreach (double element in source) {
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       return Iterate (source, decimal.MaxValue, (a, b) => Math.Min (a, b));
+               }
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+               public static int? Min (this IEnumerable<int?> source)
+               {
+                       Check.Source (source);
+
+                       return IterateNullable (source, (a, b) => Math.Min (a, b));
                }
 
+               public static long? Min (this IEnumerable<long?> source)
+               {
+                       Check.Source (source);
+
+                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+               }
 
                public static double? Min (this IEnumerable<double?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       double? minimum = double.MaxValue;
-                       foreach (double? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
-               }
+                       Check.Source (source);
 
+                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+               }
 
-               public static decimal Min (this IEnumerable<decimal> source)
+               public static float? Min (this IEnumerable<float?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       decimal minimum = decimal.MaxValue;
-                       int counter = 0;
-                       foreach (decimal element in source) {
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
-
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return IterateNullable (source, (a, b) => Math.Min (a, b));
                }
 
-
                public static decimal? Min (this IEnumerable<decimal?> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool onlyNull = true;
-                       decimal? minimum = decimal.MaxValue;
-                       foreach (decimal? element in source) {
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
-               }
+                       Check.Source (source);
 
+                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+               }
 
                public static TSource Min<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
                        bool notAssigned = true;
                        TSource minimum = default (TSource);
@@ -1612,180 +1384,79 @@ namespace System.Linq
                                return minimum;
                }
 
-
-               public static int Min<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, int> selector)
+               public static int Min<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       int minimum = int.MaxValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               int element = selector (item);
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return Iterate (source, int.MaxValue, (a, b) => Math.Min (selector (a), b));
                }
 
-
-               public static int? Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, int?> selector)
+               public static long Min<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       int? minimum = int.MaxValue;
-                       foreach (TSource item in source) {
-                               int? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
+                       return Iterate (source, long.MaxValue, (a, b) => Math.Min (selector (a), b));
                }
 
-
-               public static long Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, long> selector)
+               public static double Min<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       long minimum = long.MaxValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               long element = selector (item);
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return Iterate (source, double.MaxValue, (a, b) => Math.Min (selector (a), b));
                }
 
-
-               public static long? Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, long?> selector)
+               public static float Min<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       long? minimum = long.MaxValue;
-                       foreach (TSource item in source) {
-                               long? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
+                       return Iterate (source, float.MaxValue, (a, b) => Math.Min (selector (a), b));
                }
 
-
-               public static double Min<TSource> (this IEnumerable<TSource> source,
-                       Func<TSource, double> selector)
+               public static decimal Min<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       double minimum = double.MaxValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               double element = selector (item);
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return Iterate (source, decimal.MaxValue, (a, b) => Math.Min (selector (a), b));
                }
 
-
-               public static double? Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, double?> selector)
+               public static int? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       double? minimum = double.MaxValue;
-                       foreach (TSource item in source) {
-                               double? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
+                       return IterateNullable (source, selector, (a, b) => a < b);
                }
 
-
-               public static decimal Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, decimal> selector)
+               public static long? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       decimal minimum = decimal.MaxValue;
-                       int counter = 0;
-                       foreach (TSource item in source) {
-                               decimal element = selector (item);
-                               if (element < minimum)
-                                       minimum = element;
-                               counter++;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       if (counter == 0)
-                               throw new InvalidOperationException ();
-                       else
-                               return minimum;
+                       return IterateNullable (source, selector, (a, b) => a < b);
                }
 
+               public static float? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return IterateNullable (source, selector, (a, b) => a < b);
+               }
 
-               public static decimal? Min<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, decimal?> selector)
+               public static double? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       bool onlyNull = true;
-                       decimal? minimum = decimal.MaxValue;
-                       foreach (TSource item in source) {
-                               decimal? element = selector (item);
-                               if (element.HasValue) {
-                                       onlyNull = false;
-                                       if (element < minimum)
-                                               minimum = element;
-                               }
-                       }
-                       return (onlyNull ? null : minimum);
+                       return IterateNullable (source, selector, (a, b) => a < b);
                }
 
+               public static decimal? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return IterateNullable (source, selector, (a, b) => a < b);
+               }
 
-               public static TResult Min<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, TResult> selector)
+               public static TResult Min<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
                        bool notAssigned = true;
                        TResult minimum = default (TResult);
@@ -1822,9 +1493,13 @@ namespace System.Linq
 
                public static IEnumerable<TResult> OfType<TResult> (this IEnumerable source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
+                       return CreateOfTypeIterator<TResult> (source);
+               }
+
+               static IEnumerable<TResult> CreateOfTypeIterator<TResult> (IEnumerable source)
+               {
                        foreach (object element in source)
                                if (element is TResult)
                                        yield return (TResult) element;
@@ -1840,16 +1515,13 @@ namespace System.Linq
                        return OrderBy<TSource, TKey> (source, keySelector, null);
                }
 
-
                public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey> (this IEnumerable<TSource> source,
                                Func<TSource, TKey> keySelector,
                                IComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeySelector (source, keySelector);
 
-                       return new InternalOrderedSequence<TSource, TKey> (
-                                       source, keySelector, comparer, false);
+                       return new OrderedSequence<TSource, TKey> (source, keySelector, comparer, SortDirection.Ascending);
                }
 
                #endregion
@@ -1862,15 +1534,12 @@ namespace System.Linq
                        return OrderByDescending<TSource, TKey> (source, keySelector, null);
                }
 
-
                public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey> (this IEnumerable<TSource> source,
                                Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeySelector (source, keySelector);
 
-                       return new InternalOrderedSequence<TSource, TKey> (
-                                       source, keySelector, comparer, true);
+                       return new OrderedSequence<TSource, TKey> (source, keySelector, comparer, SortDirection.Descending);
                }
 
                #endregion
@@ -1879,10 +1548,20 @@ namespace System.Linq
 
                public static IEnumerable<int> Range (int start, int count)
                {
-                       if (count < 0 || (start + count - 1) > int.MaxValue)
+                       if (count < 0)
+                               throw new ArgumentOutOfRangeException ("count");
+
+                       long upto = ((long) start + count) - 1;
+
+                       if (upto > int.MaxValue)
                                throw new ArgumentOutOfRangeException ();
 
-                       for (int i = start; i < (start + count - 1); i++)
+                       return CreateRangeIterator (start, (int) upto);
+               }
+
+               static IEnumerable<int> CreateRangeIterator (int start, int upto)
+               {
+                       for (int i = start; i <= upto; i++)
                                yield return i;
                }
 
@@ -1895,46 +1574,62 @@ namespace System.Linq
                        if (count < 0)
                                throw new ArgumentOutOfRangeException ();
 
+                       return CreateRepeatIterator (element, count);
+               }
+
+               static IEnumerable<TResult> CreateRepeatIterator<TResult> (TResult element, int count)
+               {
                        for (int i = 0; i < count; i++)
                                yield return element;
                }
 
                #endregion
 
-
                #region Reverse
 
                public static IEnumerable<TSource> Reverse<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
+
+                       var list = source as IList<TSource>;
+                       if (list == null)
+                               list = new List<TSource> (source);
+
+                       return CreateReverseIterator (list);
+               }
 
-                       List<TSource> list = new List<TSource> (source);
-                       list.Reverse ();
-                       return list;
+               static IEnumerable<TSource> CreateReverseIterator<TSource> (IList<TSource> source)
+               {
+                       for (int i = source.Count; i > 0; --i)
+                               yield return source [i - 1];
                }
 
                #endregion
 
                #region Select
 
-               public static IEnumerable<TResult> Select<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, TResult> selector)
+               public static IEnumerable<TResult> Select<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       foreach (TSource element in source)
-                               yield return selector (element);
+                       return CreateSelectIterator (source, selector);
                }
 
+               static IEnumerable<TResult> CreateSelectIterator<TSource, TResult> (IEnumerable<TSource> source, Func<TSource, TResult> selector)
+               {
+                       foreach (var element in source)
+                               yield return selector (element);
+               }
 
-               public static IEnumerable<TResult> Select<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, int, TResult> selector)
+               public static IEnumerable<TResult> Select<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
+                       return CreateSelectIterator (source, selector);
+               }
+
+               static IEnumerable<TResult> CreateSelectIterator<TSource, TResult> (IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
+               {
                        int counter = 0;
                        foreach (TSource element in source) {
                                yield return selector (element, counter);
@@ -1946,27 +1641,32 @@ namespace System.Linq
 
                #region SelectMany
 
-               public static IEnumerable<TResult> SelectMany<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, IEnumerable<TResult>> selector)
+               public static IEnumerable<TResult> SelectMany<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
+                       return CreateSelectManyIterator (source, selector);
+               }
+
+               static IEnumerable<TResult> CreateSelectManyIterator<TSource, TResult> (IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
+               {
                        foreach (TSource element in source)
                                foreach (TResult item in selector (element))
                                        yield return item;
                }
 
-
-               public static IEnumerable<TResult> SelectMany<TSource, TResult> (this IEnumerable<TSource> source,
-                               Func<TSource, int, IEnumerable<TResult>> selector)
+               public static IEnumerable<TResult> SelectMany<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
+                       return CreateSelectManyIterator (source, selector);
+               }
+
+               static IEnumerable<TResult> CreateSelectManyIterator<TSource, TResult> (IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
+               {
                        int counter = 0;
                        foreach (TSource element in source) {
-                               foreach (TResult item in selector (element, counter++))
+                               foreach (TResult item in selector (element, counter))
                                        yield return item;
                                counter++;
                        }
@@ -1975,20 +1675,30 @@ namespace System.Linq
                public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult> (this IEnumerable<TSource> source,
                        Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> selector)
                {
-                       if (source == null || collectionSelector == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndCollectionSelectors (source, collectionSelector, selector);
+
+                       return CreateSelectManyIterator (source, collectionSelector, selector);
+               }
 
+               static IEnumerable<TResult> CreateSelectManyIterator<TSource, TCollection, TResult> (IEnumerable<TSource> source,
+                       Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> selector)
+               {
                        foreach (TSource element in source)
                                foreach (TCollection collection in collectionSelector (element))
                                        yield return selector (element, collection);
                }
 
                public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult> (this IEnumerable<TSource> source,
-               Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> selector)
+                       Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> selector)
                {
-                       if (source == null || collectionSelector == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndCollectionSelectors (source, collectionSelector, selector);
+
+                       return CreateSelectManyIterator (source, collectionSelector, selector);
+               }
 
+               static IEnumerable<TResult> CreateSelectManyIterator<TSource, TCollection, TResult> (IEnumerable<TSource> source,
+                       Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> selector)
+               {
                        int counter = 0;
                        foreach (TSource element in source)
                                foreach (TCollection collection in collectionSelector (element, counter++))
@@ -1999,46 +1709,40 @@ namespace System.Linq
 
                #region Single
 
-               public static TSource Single<TSource> (this IEnumerable<TSource> source)
+               static TSource Single<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate, Fallback fallback)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       var found = false;
+                       var item = default (TSource);
 
-                       bool otherElement = false;
-                       TSource singleElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (otherElement) throw new InvalidOperationException ();
-                               if (!otherElement) otherElement = true;
-                               singleElement = element;
+                       foreach (var element in source) {
+                               if (!predicate (element))
+                                       continue;
+
+                               if (found)
+                                       throw new InvalidOperationException ();
+
+                               found = true;
+                               item = element;
                        }
 
-                       if (otherElement)
-                               return singleElement;
-                       else
+                       if (!found && fallback == Fallback.Throw)
                                throw new InvalidOperationException ();
-               }
 
+                       return item;
+               }
 
-               public static TSource Single<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, bool> predicate)
+               public static TSource Single<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       bool otherElement = false;
-                       TSource singleElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (predicate (element)) {
-                                       if (otherElement) throw new InvalidOperationException ();
-                                       if (!otherElement) otherElement = true;
-                                       singleElement = element;
-                               }
-                       }
+                       return source.Single (PredicateOf<TSource>.Always, Fallback.Throw);
+               }
 
-                       if (otherElement)
-                               return singleElement;
-                       else
-                               throw new InvalidOperationException ();
+               public static TSource Single<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return source.Single (predicate, Fallback.Throw);
                }
 
                #endregion
@@ -2047,67 +1751,53 @@ namespace System.Linq
 
                public static TSource SingleOrDefault<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       bool otherElement = false;
-                       TSource singleElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (otherElement) throw new InvalidOperationException ();
-                               if (!otherElement) otherElement = true;
-                               singleElement = element;
-                       }
+                       Check.Source (source);
 
-                       return singleElement;
+                       return source.Single (PredicateOf<TSource>.Always, Fallback.Default);
                }
 
-
-               public static TSource SingleOrDefault<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, bool> predicate)
+               public static TSource SingleOrDefault<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
-
-                       bool otherElement = false;
-                       TSource singleElement = default (TSource);
-                       foreach (TSource element in source) {
-                               if (predicate (element)) {
-                                       if (otherElement) throw new InvalidOperationException ();
-                                       if (!otherElement) otherElement = true;
-                                       singleElement = element;
-                               }
-                       }
+                       Check.SourceAndPredicate (source, predicate);
 
-                       return singleElement;
+                       return source.Single (predicate, Fallback.Default);
                }
 
                #endregion
 
                #region Skip
+
                public static IEnumerable<TSource> Skip<TSource> (this IEnumerable<TSource> source, int count)
                {
-                       if (source == null)
-                               throw new NotSupportedException ();
+                       Check.Source (source);
 
+                       return CreateSkipIterator (source, count);
+               }
+
+               static IEnumerable<TSource> CreateSkipIterator<TSource> (IEnumerable<TSource> source, int count)
+               {
                        int i = 0;
-                       foreach (TSource e in source) {
-                               if (++i < count)
+                       foreach (var element in source) {
+                               if (i++ < count)
                                        continue;
-                               yield return e;
+
+                               yield return element;
                        }
                }
+
                #endregion
 
                #region SkipWhile
 
-
-               public static IEnumerable<TSource> SkipWhile<TSource> (
-                               this IEnumerable<TSource> source,
-                               Func<TSource, bool> predicate)
+               public static IEnumerable<TSource> SkipWhile<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return CreateSkipWhileIterator (source, predicate);
+               }
 
+               static IEnumerable<TSource> CreateSkipWhileIterator<TSource> (IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
                        bool yield = false;
 
                        foreach (TSource element in source) {
@@ -2121,13 +1811,15 @@ namespace System.Linq
                        }
                }
 
-
-               public static IEnumerable<TSource> SkipWhile<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, int, bool> predicate)
+               public static IEnumerable<TSource> SkipWhile<TSource> (this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return CreateSkipWhileIterator (source, predicate);
+               }
 
+               static IEnumerable<TSource> CreateSkipWhileIterator<TSource> (IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
+               {
                        int counter = 0;
                        bool yield = false;
 
@@ -2149,245 +1841,203 @@ namespace System.Linq
 
                public static int Sum (this IEnumerable<int> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
-
-                       int sum = 0;
-                       foreach (int element in source)
-                               sum += element;
+                       Check.Source (source);
 
-                       return sum;
+                       return Sum<int, int> (source, (a, b) => checked (a + b));
                }
 
-
-               public static int Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
+               public static int? Sum (this IEnumerable<int?> source)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       int sum = 0;
-                       foreach (TSource element in source)
-                               sum += selector (element);
+                       Check.Source (source);
 
-                       return sum;
+                       return source.SumNullable<int?, int?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
                }
 
-
-               public static int? Sum (this IEnumerable<int?> source)
+               public static int Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       int? sum = 0;
-                       foreach (int? element in source)
-                               if (element.HasValue)
-                                       sum += element.Value;
+                       Check.SourceAndSelector (source, selector);
 
-                       return sum;
+                       return Sum<TSource, int> (source, (a, b) => checked (a + selector (b)));
                }
 
-
                public static int? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       int? sum = 0;
-                       foreach (TSource element in source) {
-                               int? item = selector (element);
-                               if (item.HasValue)
-                                       sum += item.Value;
-                       }
+                       Check.SourceAndSelector (source, selector);
 
-                       return sum;
+                       return source.SumNullable<TSource, int?> (0, (a, b) => {
+                               var value = selector (b);
+                               return value.HasValue ? checked (a + value.Value) : a;
+                       });
                }
 
-
                public static long Sum (this IEnumerable<long> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       long sum = 0;
-                       foreach (long element in source)
-                               sum += element;
-
-                       return sum;
+                       return Sum<long, long> (source, (a, b) => checked (a + b));
                }
 
-
-               public static long Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
+               public static long? Sum (this IEnumerable<long?> source)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       long sum = 0;
-                       foreach (TSource element in source)
-                               sum += selector (element);
-
-                       return sum;
+                       return source.SumNullable<long?, long?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
                }
 
-
-               public static long? Sum (this IEnumerable<long?> source)
+               public static long Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       long? sum = 0;
-                       foreach (long? element in source)
-                               if (element.HasValue)
-                                       sum += element.Value;
-
-                       return sum;
+                       return Sum<TSource, long> (source, (a, b) => checked (a + selector (b)));
                }
 
-
                public static long? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       long? sum = 0;
-                       foreach (TSource element in source) {
-                               long? item = selector (element);
-                               if (item.HasValue)
-                                       sum += item.Value;
-                       }
-
-                       return sum;
+                       return source.SumNullable<TSource, long?> (0, (a, b) => {
+                               var value = selector (b);
+                               return value.HasValue ? checked (a + value.Value) : a;
+                       });
                }
 
-
                public static double Sum (this IEnumerable<double> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       double sum = 0;
-                       foreach (double element in source)
-                               sum += element;
+                       Check.Source (source);
 
-                       return sum;
+                       return Sum<double, double> (source, (a, b) => checked (a + b));
                }
 
+               public static double? Sum (this IEnumerable<double?> source)
+               {
+                       Check.Source (source);
+
+                       return source.SumNullable<double?, double?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+               }
 
                public static double Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       double sum = 0;
-                       foreach (TSource element in source)
-                               sum += selector (element);
+                       Check.SourceAndSelector (source, selector);
 
-                       return sum;
+                       return Sum<TSource, double> (source, (a, b) => checked (a + selector (b)));
                }
 
-
-               public static double? Sum (this IEnumerable<double?> source)
+               public static double? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndSelector (source, selector);
 
-                       double? sum = 0;
-                       foreach (double? element in source)
-                               if (element.HasValue)
-                                       sum += element.Value;
-
-                       return sum;
+                       return source.SumNullable<TSource, double?> (0, (a, b) => {
+                               var value = selector (b);
+                               return value.HasValue ? checked (a + value.Value) : a;
+                       });
                }
 
+               public static float Sum (this IEnumerable<float> source)
+               {
+                       Check.Source (source);
 
-               public static double? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
+                       return Sum<float, float> (source, (a, b) => checked (a + b));
+               }
+
+               public static float? Sum (this IEnumerable<float?> source)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       double? sum = 0;
-                       foreach (TSource element in source) {
-                               double? item = selector (element);
-                               if (item.HasValue)
-                                       sum += item.Value;
-                       }
+                       return source.SumNullable<float?, float?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+               }
 
-                       return sum;
+               public static float Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return Sum<TSource, float> (source, (a, b) => checked (a + selector (b)));
                }
 
+               public static float? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
+
+                       return source.SumNullable<TSource, float?> (0, (a, b) => {
+                               var value = selector (b);
+                               return value.HasValue ? checked (a + value.Value) : a;
+                       });
+               }
 
                public static decimal Sum (this IEnumerable<decimal> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
-                       decimal sum = 0;
-                       foreach (decimal element in source)
-                               sum += element;
-
-                       return sum;
+                       return Sum<decimal, decimal> (source, (a, b) => checked (a + b));
                }
 
+               public static decimal? Sum (this IEnumerable<decimal?> source)
+               {
+                       Check.Source (source);
+
+                       return source.SumNullable<decimal?, decimal?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+               }
 
                public static decimal Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
-
-                       decimal sum = 0;
-                       foreach (TSource element in source)
-                               sum += selector (element);
+                       Check.SourceAndSelector (source, selector);
 
-                       return sum;
+                       return Sum<TSource, decimal> (source, (a, b) => checked (a + selector (b)));
                }
 
-
-               public static decimal? Sum (this IEnumerable<decimal?> source)
+               public static decimal? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
-
-                       decimal? sum = 0;
-                       foreach (decimal? element in source)
-                               if (element.HasValue)
-                                       sum += element.Value;
+                       Check.SourceAndSelector (source, selector);
 
-                       return sum;
+                       return source.SumNullable<TSource, decimal?> (0, (a, b) => {
+                               var value = selector (b);
+                               return value.HasValue ? checked (a + value.Value) : a;
+                       });
                }
 
-
-               public static decimal? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
+               static TR Sum<TA, TR> (this IEnumerable<TA> source, Func<TR, TA, TR> selector)
                {
-                       if (source == null || selector == null)
-                               throw new ArgumentNullException ();
+                       TR total = default (TR);
+                       long counter = 0;
+                       foreach (var element in source) {
+                               total = selector (total, element);
+                               ++counter;
+                       }
 
-                       decimal? sum = 0;
-                       foreach (TSource element in source) {
-                               decimal? item = selector (element);
-                               if (item.HasValue)
-                                       sum += item.Value;
+                       return total;
+               }
+
+               static TR SumNullable<TA, TR> (this IEnumerable<TA> source, TR zero, Func<TR, TA, TR> selector)
+               {
+                       TR total = zero;
+                       foreach (var element in source) {
+                               total = selector (total, element);
                        }
 
-                       return sum;
+                       return total;
                }
 
                #endregion
+
                #region Take
 
                public static IEnumerable<TSource> Take<TSource> (this IEnumerable<TSource> source, int count)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
 
+                       return CreateTakeIterator (source, count);
+               }
+
+               static IEnumerable<TSource> CreateTakeIterator<TSource> (IEnumerable<TSource> source, int count)
+               {
                        if (count <= 0)
                                yield break;
-                       else {
-                               int counter = 0;
-                               foreach (TSource element in source) {
-                                       yield return element;
-                                       counter++;
-                                       if (counter == count)
-                                               yield break;
-                               }
+
+                       int counter = 0;
+                       foreach (TSource element in source) {
+                               yield return element;
+
+                               if (++counter == count)
+                                       yield break;
                        }
                }
 
@@ -2397,28 +2047,36 @@ namespace System.Linq
 
                public static IEnumerable<TSource> TakeWhile<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
-                       foreach (TSource element in source) {
-                               if (predicate (element))
-                                       yield return element;
-                               else
+                       return CreateTakeWhileIterator (source, predicate);
+               }
+
+               static IEnumerable<TSource> CreateTakeWhileIterator<TSource> (IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
+                       foreach (var element in source) {
+                               if (!predicate (element))
                                        yield break;
+
+                               yield return element;
                        }
                }
 
                public static IEnumerable<TSource> TakeWhile<TSource> (this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
+
+                       return CreateTakeWhileIterator (source, predicate);
+               }
 
+               static IEnumerable<TSource> CreateTakeWhileIterator<TSource> (IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
+               {
                        int counter = 0;
-                       foreach (TSource element in source) {
-                               if (predicate (element, counter))
-                                       yield return element;
-                               else
+                       foreach (var element in source) {
+                               if (!predicate (element, counter))
                                        yield break;
+
+                               yield return element;
                                counter++;
                        }
                }
@@ -2432,12 +2090,10 @@ namespace System.Linq
                        return ThenBy<TSource, TKey> (source, keySelector, null);
                }
 
-
                public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey> (this IOrderedEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeySelector (source, keySelector);
 
                        return source.CreateOrderedEnumerable (keySelector, comparer, false);
                }
@@ -2452,12 +2108,10 @@ namespace System.Linq
                        return ThenByDescending<TSource, TKey> (source, keySelector, null);
                }
 
-
                public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey> (this IOrderedEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeySelector (source, keySelector);
 
                        return source.CreateOrderedEnumerable (keySelector, comparer, true);
                }
@@ -2465,47 +2119,63 @@ namespace System.Linq
                #endregion
 
                #region ToArray
+
                public static TSource [] ToArray<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ();
+                       Check.Source (source);
+
+                       var collection = source as ICollection<TSource>;
+                       if (collection != null) {
+                               var array = new TSource [collection.Count];
+                               collection.CopyTo (array, 0);
+                               return array;
+                       }
 
-                       List<TSource> list = new List<TSource> (source);
-                       return list.ToArray ();
+                       return new List<TSource> (source).ToArray ();
                }
 
                #endregion
 
                #region ToDictionary
-               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
+               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this IEnumerable<TSource> source,
+                               Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
                {
                        return ToDictionary<TSource, TKey, TElement> (source, keySelector, elementSelector, null);
                }
 
-
-               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
+               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this IEnumerable<TSource> source,
+                               Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
-                       if (keySelector == null)
-                               throw new ArgumentNullException ("keySelector");
-                       if (elementSelector == null)
-                               throw new ArgumentNullException ("elementSelector");
-
-                       Dictionary<TKey, TElement> dict = new Dictionary<TKey, TElement> (comparer);
-                       foreach (TSource e in source) {
+                       Check.SourceAndKeyElementSelectors (source, keySelector, elementSelector);
+
+                       if (comparer == null)
+                               comparer = EqualityComparer<TKey>.Default;
+
+                       var dict = new Dictionary<TKey, TElement> (comparer);
+                       foreach (var e in source)
                                dict.Add (keySelector (e), elementSelector (e));
-                       }
 
                        return dict;
                }
+
+               public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey> (this IEnumerable<TSource> source,
+                               Func<TSource, TKey> keySelector)
+               {
+                       return ToDictionary (source, keySelector, null);
+               }
+
+               public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey> (this IEnumerable<TSource> source,
+                               Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
+               {
+                       return ToDictionary<TSource, TKey, TSource> (source, keySelector, Function<TSource>.Identity, comparer);
+               }
+
                #endregion
 
                #region ToList
                public static List<TSource> ToList<TSource> (this IEnumerable<TSource> source)
                {
-                       if (source == null)
-                               throw new ArgumentNullException ("source");
+                       Check.Source (source);
 
                        return new List<TSource> (source);
                }
@@ -2513,84 +2183,110 @@ namespace System.Linq
 
                #region ToLookup
 
-               public static Lookup<TKey, TSource> ToLookup<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
+               public static ILookup<TKey, TSource> ToLookup<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
                {
-                       return ToLookup<TSource, TKey> (source, keySelector, null);
+                       return ToLookup<TSource, TKey, TSource> (source, keySelector, Function<TSource>.Identity, null);
                }
 
-
-               public static Lookup<TKey, TSource> ToLookup<TSource, TKey> (this IEnumerable<TSource> source,
+               public static ILookup<TKey, TSource> ToLookup<TSource, TKey> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null)
-                               throw new ArgumentNullException ();
-
-                       Dictionary<TKey, List<TSource>> dictionary = new Dictionary<TKey, List<TSource>> (comparer ?? EqualityComparer<TKey>.Default);
-                       foreach (TSource element in source) {
-                               TKey key = keySelector (element);
-                               if (key == null)
-                                       throw new ArgumentNullException ();
-                               if (!dictionary.ContainsKey (key))
-                                       dictionary.Add (key, new List<TSource> ());
-                               dictionary [key].Add (element);
-                       }
-                       return new Lookup<TKey, TSource> (dictionary);
+                       return ToLookup<TSource, TKey, TSource> (source, keySelector, element => element, comparer);
                }
 
-
-               public static Lookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this IEnumerable<TSource> source,
+               public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
                {
                        return ToLookup<TSource, TKey, TElement> (source, keySelector, elementSelector, null);
                }
 
-
-               public static Lookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this IEnumerable<TSource> source,
+               public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this IEnumerable<TSource> source,
                        Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
                {
-                       if (source == null || keySelector == null || elementSelector == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndKeyElementSelectors (source, keySelector, elementSelector);
 
-                       Dictionary<TKey, List<TElement>> dictionary = new Dictionary<TKey, List<TElement>> (comparer ?? EqualityComparer<TKey>.Default);
-                       foreach (TSource element in source) {
-                               TKey key = keySelector (element);
+                       var dictionary = new Dictionary<TKey, List<TElement>> (comparer ?? EqualityComparer<TKey>.Default);
+                       foreach (var element in source) {
+                               var key = keySelector (element);
                                if (key == null)
-                                       throw new ArgumentNullException ();
-                               if (!dictionary.ContainsKey (key))
-                                       dictionary.Add (key, new List<TElement> ());
-                               dictionary [key].Add (elementSelector (element));
+                                       throw new ArgumentNullException ("key");
+
+                               List<TElement> list;
+                               if (!dictionary.TryGetValue (key, out list)) {
+                                       list = new List<TElement> ();
+                                       dictionary.Add (key, list);
+                               }
+
+                               list.Add (elementSelector (element));
                        }
+
                        return new Lookup<TKey, TElement> (dictionary);
                }
 
                #endregion
 
-               #region ToSequence
+               #region SequenceEqual
+
+               public static bool SequenceEqual<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second)
+               {
+                       return first.SequenceEqual (second, null);
+               }
 
-               public static IEnumerable<T> ToSequence<T> (this IEnumerable<T> source)
+               public static bool SequenceEqual<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
                {
-                       return (IEnumerable<T>) source;
+                       Check.FirstAndSecond (first, second);
+
+                       if (comparer == null)
+                               comparer = EqualityComparer<TSource>.Default;
+
+                       using (IEnumerator<TSource> first_enumerator = first.GetEnumerator (),
+                               second_enumerator = second.GetEnumerator ()) {
+
+                               while (first_enumerator.MoveNext ()) {
+                                       if (!second_enumerator.MoveNext ())
+                                               return false;
+
+                                       if (!comparer.Equals (first_enumerator.Current, second_enumerator.Current))
+                                               return false;
+                               }
+
+                               return !second_enumerator.MoveNext ();
+                       }
                }
 
                #endregion
 
                #region Union
 
-
                public static IEnumerable<TSource> Union<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second)
                {
-                       if (first == null || second == null)
-                               throw new ArgumentNullException ();
+                       Check.FirstAndSecond (first, second);
 
-                       List<TSource> items = new List<TSource> ();
-                       foreach (TSource element in first) {
-                               if (IndexOf (items, element) == -1) {
+                       return first.Union (second, null);
+               }
+
+               public static IEnumerable<TSource> Union<TSource> (this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
+               {
+                       Check.FirstAndSecond (first, second);
+
+                       if (comparer == null)
+                               comparer = EqualityComparer<TSource>.Default;
+
+                       return CreateUnionIterator (first, second, comparer);
+               }
+
+               static IEnumerable<TSource> CreateUnionIterator<TSource> (IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
+               {
+                       var items = new HashSet<TSource> (comparer);
+                       foreach (var element in first) {
+                               if (! items.Contains (element)) {
                                        items.Add (element);
                                        yield return element;
                                }
                        }
-                       foreach (TSource element in second) {
-                               if (IndexOf (items, element) == -1) {
+
+                       foreach (var element in second) {
+                               if (! items.Contains (element, comparer)) {
                                        items.Add (element);
                                        yield return element;
                                }
@@ -2601,24 +2297,29 @@ namespace System.Linq
 
                #region Where
 
-               public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, bool> predicate)
+               public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
+                       return CreateWhereIterator (source, predicate);
+               }
+
+               static IEnumerable<TSource> CreateWhereIterator<TSource> (IEnumerable<TSource> source, Func<TSource, bool> predicate)
+               {
                        foreach (TSource element in source)
                                if (predicate (element))
                                        yield return element;
                }
 
-
-               public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source,
-                               Func<TSource, int, bool> predicate)
+               public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
                {
-                       if (source == null || predicate == null)
-                               throw new ArgumentNullException ();
+                       Check.SourceAndPredicate (source, predicate);
 
+                       return CreateWhereIterator (source, predicate);
+               }
+
+               static IEnumerable<TSource> CreateWhereIterator<TSource> (this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
+               {
                        int counter = 0;
                        foreach (TSource element in source) {
                                if (predicate (element, counter))
@@ -2629,61 +2330,20 @@ namespace System.Linq
 
                #endregion
 
-               // These methods are not included in the
-               // .NET Standard Query Operators Specification,
-               // but they provide additional useful commands
-
-               #region Compare
-
-               private static bool Equals<T> (T first, T second)
-               {
-                       // Mostly, values in Enumerable<T> 
-                       // sequences need to be compared using
-                       // Equals and GetHashCode
-
-                       if (first == null || second == null)
-                               return (first == null && second == null);
-                       else
-                               return ((first.Equals (second) ||
-                                                first.GetHashCode () == second.GetHashCode ()));
-               }
-
-               #endregion
-
-               #region IndexOf
-
-               static int IndexOf<T> (this IEnumerable<T> source, T item, IEqualityComparer<T> comparer)
-               {
-                       if (comparer == null)
-                               comparer = EqualityComparer<T>.Default;
-
-                       int counter = 0;
-                       foreach (T element in source) {
-                               if (comparer.Equals (element, item))
-                                       return counter;
-                               counter++;
-                       }
-                       // The item was not found
-                       return -1;
-               }
-
-               static int IndexOf<T> (this IEnumerable<T> source, T item)
-               {
-                       return IndexOf<T> (source, item, null);
+               class ReadOnlyCollectionOf<T> {
+                       public static readonly ReadOnlyCollection<T> Empty = new ReadOnlyCollection<T> (new T [0]);
                }
-               #endregion
 
-               #region ToReadOnlyCollection
-               internal static ReadOnlyCollection<TSource> ToReadOnlyCollection<TSource> (IEnumerable<TSource> source)
+               internal static ReadOnlyCollection<TSource> ToReadOnlyCollection<TSource> (this IEnumerable<TSource> source)
                {
                        if (source == null)
-                               return new ReadOnlyCollection<TSource> (new List<TSource> ());
+                               return ReadOnlyCollectionOf<TSource>.Empty;
 
-                       if (typeof (ReadOnlyCollection<TSource>).IsInstanceOfType (source))
-                               return source as ReadOnlyCollection<TSource>;
+                       var ro = source as ReadOnlyCollection<TSource>;
+                       if (ro != null)
+                               return ro;
 
-                       return new ReadOnlyCollection<TSource> (ToArray<TSource> (source));
+                       return new ReadOnlyCollection<TSource> (source.ToArray<TSource> ());
                }
-               #endregion
        }
 }