Sorting custom objects in CSharp

Recently I had to figure out a way to sort a large amount of data coming back from a web service call that I had put into a List of custom objects to store the returned data individually.

Turned out there is a Sort() method for Lists in CSharp that has the power to dig into lists and sort your data, even for custom objects.

So, in my case I had a custom object called TheQuote which stored data from the web service response. I wanted to order this data based on a value of TheQuotes object called Premium.

This is how I did it, I set up my list.

List<TheQuote> theQuoteResults = new List<TheQuote>();

I then filled out my List theQuoteResults using a foreach loop working through the web service response data and adding in a TheQuote object at the end of each loop.

theQuoteResults.Add(theQuote);

Then came the cool part, the sort method.

theQuoteResults.Sort(delegate(TheQuote q1, TheQuote q2) {

return q1.Premium.CompareTo(q2.Premium);

});

Now my list was sorted based on the double value Premium in my TheQuote object. Pretty nifty.

Resource: DeveloperFusion.com

blog comments powered by Disqus