Skip to main content

...

....

C# Snippet Tutorial - Custom List Sorting [Beginner]


The List is one of my favorite additions to the .NET framework. It has built-in mechanisms to perform efficient sorting and searching. In this snippet tutorial, I'm going to demonstrate how to customize the sorting routines used by the List class.

The default Sort function of the List uses the CompareTo method of the object if it implements IComparable. Fortunately, the .NET primitives already implement this interface, which means to sort a List of primitives, you don't have to do anything special.
List<string> myList = new List<string>();

myList.Add("one");
myList.Add("two");
myList.Add("three");
myList.Add("four");

myList.Sort();

foreach (string s in myList)
  Console.WriteLine(s); 
Output:
four
one
three
two
 
With that being said, to get the List to sort your own custom objects, all you'd have to do is have your object implement the IComparable interface.
public class MyObject : IComparable<MyObject>
{
  private int _myInt;

  public int MyInt
  {
    get { return _myInt; }
    set { _myInt = value; }
  }

  public MyObject(int value)
  {
    _myInt = value;
  }

  public int CompareTo(MyObject obj)
  {
    return _myInt.CompareTo(obj.MyInt);
  }
}
 
And here's what happens when you populate and sort a list of these objects.
List<MyObject> myObjectList = new List<MyObject>();

myObjectList.Add(new MyObject(3));
myObjectList.Add(new MyObject(1));
myObjectList.Add(new MyObject(4));
myObjectList.Add(new MyObject(2));

myObjectList.Sort();

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);
Output:
1
2
3
4
 
That works great when you have access to the object, but what happens if you want to sort an object that doesn't implement IComparable? Good thing for us, the Sort method can take an IComparer, which will take its place. If the object that is being sorted also implements IComparable, passing an IComparer will override the CompareTo function located inside the object.

Let's specify an IComparer that will sort the previous List in the opposite direction.
public class MyListSorter : IComparer<MyObject>
{
  public int Compare(MyObject obj1, MyObject obj2)
  {
    return obj2.CompareTo(obj1);
  }
}
 
Just like with the CompareTo function, the Compare function returns less than zero if the first object precedes the second one, 0 if they are identical, and greater than zero if the second object precedes the first. Since I'm comparing primitive types, I simply used their CompareTo function. Here's how we use this object.
myObjectList.Sort(new MyListSorter());

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);
Output:
4
3
2
1
 
If you don't want to go through all the work of creating a new object to do your comparisons, the last way to sort a List is to use a function. Here's the same sorting using a Comparison delegate.
public int MySortFunction(MyObject obj1, MyObject obj2)
{
  return obj2.CompareTo(obj1);
}

myObjectList.Sort(new Comparison<MyObject>(MySortFunction));

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);
Output:
4
3
2
1
 
That's it for sorting a List. The sort function has another override not shown here that specifies the range to sort, but I'm sure you can figure out how to use that by yourself.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV