The Self-Taught Programmer

Recipes from real-world experience with

How to Sort a Generic List of Objects

leave a comment »

The Situation

You are trying to sort a Generic List of Objects based on a property of the Objects.

A Solution

There are two easy options for sorting a Generic List populated with Objects: in place and sorting to a new List. Use Linq.

“In Place” sorting of an existing List (the code below only works with text fields):

using System.Linq;

Users.Sort((a, b) => string.Compare(a.LastName, b.LastName));

Sort a List to a new list:

List<Users> UserList = Users.OrderBy(o => o.LastName).ToList();

Written by Jim McMullen

January 2, 2014 at 5:08 pm

Posted in How-To

Tagged with ,

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: