How to Sort a Generic List of Objects

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();

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 )

Connecting to %s