tags:

views:

81

answers:

6

Hello,

I have a List object that includes 3 items: Partial, Full To H, and Full To O.

I'm binding this list to an asp OptionButtonList, and it's sorting it in alphabetical order. However, I want to sort the list like the following:

Full To H, Partial, Full To O.

How can I accomplish this?

Thanks! V

A: 

Linq is great for this. You could even build the order sequence up to have it defined on the fly since the execution of the sort is not executed until the ToList.

 var sortedList = yourList.OrderBy(i => i.FullToH).
     ThenBy(i => i.Partial).
     ThenBy(i => i.FullToO).ToList();
Kelsey
A: 

Create a Comparer for your custom type (which implements the IComparer interface). You can then use that to sort the List:

List<CustomType> list = new List<CustomType>();

// Fill list
list.Sort(new CustomComparer());

Or if you're using a newer version of the framework and don't need to re-use the sorting logic, you could use the IEnumerable<T>.OrderBy() method.

Justin Niessner
+2  A: 

Implement IComparer for your objects.

http://devcity.net/Articles/20/1/20020304.aspx

http://support.microsoft.com/kb/321292

this. __curious_geek
+1  A: 

Are the items you listed (FullToHo for example) just strings? If so then all you need to do is to write a method to do the comparison and sort with that method.

public int CompareEntries(string left, string right) {
  const string fullToH = "Full To H";
  const string partial = "Partial";
  const string fullToO = "Full To O";
  if ( left == right ) {
    return 0;
  } else if ( left == fullToH ) {
    return -1;
  } else if ( left == fullToO ) {
    return 1;
  } else if ( right == fullToH ) {
    return 1;
  } else {
    return -1; 
  }
}

list.Sort(CompareEntries);
JaredPar
+1  A: 

Assuming that your list is not

 List<object> myList = new List<object>();

but instead, something like

List<MyObjectClass> myList = new List<MyObjectClass>();

(where each element is of the same object type)

You could do this:

myList.Sort((firstObj, secondObj) =>
    {
        return firstObj.SomeProperty.CompareTo(secondObj.SomeProperty);
    }
);
Gabriel McAdams
A: 

Thanks for everyone's help!

I did it like this:

List<string> sortedList = new List<string>();
sortedList = list.OrderBy(i => i.CodeValue == "FullToH").ThenBy(i => i.CodeValue == "Partial").ThenBy(i => i.CodeValue == "FullToO").ToList();

Then binded to the sortedList!