Reverse C# with Example
Inverts the order of the elements in a sequence. If there is no items throws a ArgumentNullException: source is null. Example: // Create an array. int[] array = { 1, 2, 3, 4 }; //Output: // Call reverse extension method on the array. //4 //3 var reverse = array.Reverse(); // Write contents of array to screen. //2 foreach (int value in reverse) //1 Console.WriteLine(value); Live code example Remeber that Reverse() may work diffrent depending on the chain order of your LINQ statements. //Create List of chars List integerlist = new List() { 1, 2, 3, 4, 5, 6 }; //Reversing the list then taking the two first elements IEnumerable reverseFirst = integerlist.Reverse().Take(2); //Taking 2 elements and then reversing only thos two IEnumerable reverseLast = integerlist.Take(2).Reverse(); //reverseFirst output: 6, 5 //reverseLast output: 2, 1 Live code example Reverse() works by buffering everything then walk through it backwards, whitch is not very efficient, but neither is OrderBy from that perspective. In LINQ-to-Objects, there are buffering operations (Reverse, OrderBy, GroupBy, etc) and non-buffering operations (Where, Take, Skip, etc). Example: Non-b uff e ri ng Reverse extention public static IEnumerable Reverse(this IList list) { for (int i = list.Count - 1; i >= 0; i--) yield return list[i]; } Live code example This method can encounter problems if u mutate the list while iterating.