C#. How to sort List by field

In this post I'll describe two ways to sort List<T> generic collection by one of it's fields. It's very useful and not easy for beginners.

We have a class "Coupon" with 3 fields. Here it is:

Let’s create and fill source List<Coupon>:


Now we need to sort this List by field "coupon_number". I usually use one of two ways for sorting List<T>, here they are.


1. Common List<T> sorting by field

We need to add class for compare


And for sorting by field "coupon_number" we need to write this string:


We don’t need to create another List<T> and we don’t need to use System.Linq, so our dll will be less size and use less resources, but we use some more code.


2. using System.Linq

Using System.Linq we need to create another List<T> and add using System.Linq. This way is good if it’s not the only using of Linq in your project.


MarkiMarta.com. Notes of web-specialist
Since 2009
Copy attachements from one SharePoint list item to another

Using this method you can copy attachments from one list item to another. You can add it to SharePoint workflow...