12,299,109 members (46,604 online)

23.8K views
19 bookmarked
Posted

# Extension Methods Exemplified: Sorting Index-based Generic Lists

, 23 Aug 2008 CPOL
This article shows how extension methods can be used, e.g., for sorting index-based generic lists.
 Sorting Extensions Properties ```﻿using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Extensions { /// /// Provides extension methods for sorting index-based generic lists. /// public static class SortingExtensionProvider { /// /// Applies the Bubble Sort algorithm to the list. /// /// Type of the list elements which implements IComparable. /// An index-based generic list. public static void Sort(this IList list) where T : IComparable { Sort(list, 0, list.Count - 1); } /// /// Applies the Bubble Sort algorithm to a range of elements of the list. /// /// Type of the list elements which implements IComparable. /// An index-based generic list. /// Index of the first element of the range. /// Index of the last element of the range. public static void Sort(this IList list, int startIndex, int endIndex) where T : IComparable { //Bubble Sort for (int i = startIndex; i < endIndex; i++) for (int j = endIndex; j > i; j--) if (list[j].IsLesserThan(list[j - 1])) list.Exchange(j, j - 1); } /// /// Exchanges two elements of the list. /// /// Type of the list elements which implements IComparable. /// An index-based generic list. /// Index of the first element to be exchanged. /// Index of the second element to be exchanged. private static void Exchange(this IList list, int index1, int index2) { T tmp = list[index1]; list[index1] = list[index2]; list[index2] = tmp; } /// /// Returns whether the value of an IComparable is lesser than the value of another. /// /// An object of a type that implements IComparable. /// An object of a type that implements IComparable. /// private static bool IsLesserThan(this IComparable value, IComparable item) { return value.CompareTo(item) < 0; } } } ```

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

## Share

 Other Leibniz Institute for Neurobiology Magdeburg Germany
- 2002 - 2004: vocational training (IT Specialist in Software Development) at the Deutsche Telekom AG with in-firm training at the T-Systems International GmbH (Berlin, Germany)

- 2003: three-month stay-abroad at the InterConsult Bulgaria Ltd. (Sofia, Bulgaria)

- 2004 - 2009: undergraduate studies in IT-Systems Engineering at the Hasso Plattner Institute for Software Systems Engineering (University of Potsdam, Germany)

- 2009: bachelor project at the Deutsche Post DHL (Berlin, Germany)

- 2009 - 2012: graduate studies in Integrative Neuroscience (Magdeburg, Germany)

- 2012 - present: research fellow at the Leibniz Institute for Neurobiology (Magdeburg, Germany)

- specialized in Microsoft .NET technologies
- currently develops scientific software with MatLab