C# How to sort a List?

A simple method to sort a list would be:

List<Account> accountList = GetAccountList();
accountList.Sort(
    delegate(Account a1, Account a2)
    {
        return a1.AccountDate.CompareTo(a2.AccountDate);
    }
);

If you need to sort the list in-place then you can use the Sort method, passing a Comparison<T> delegate:

listAccount.Sort((x, y) => x.AccountDate.CompareTo(y.AccountDate));

The second method is more preferable if you do not have to compare more than one attributes.

Advertisements

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