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

Advertisements

Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s