⌘BABAKOV.NET Let's code!
100% [light] [ru]

Sorting a List (List) in C#

Recently, I had to sort lists, and surprisingly, it turned out to be simple.

Let's say we have a class:

public class User
    {
        public int id;
        public string name;
    }



Creating a list:

List<User> usr = new List<User>();
            //Заполняем список
            User u1 = new User();
            u1.id = 2;
            u1.name = "Ольга";
            usr.Add(u1);
            u1 = new User();
            u1.id = 1;
            u1.name = "Дима";
            usr.Add(u1);
            u1 = new User();
            u1.id = 3;
            u1.name = "Света";
            usr.Add(u1);



To sort it by the ID field, we need to do just this:

usr.Sort(delegate(User us1, User us2)
            { return us1.id.CompareTo(us2.id); });



Here's what happens:
 

As you can see from the picture, I became curious about how quickly this all works.
The result surprised me, I expected something more modest.
Populated the list with 100,000 records, the first field shows the time spent filling, the second shows the time spent sorting by the ID field.
 

The source code for the example can be downloaded here:
testlistsort.rar · 18 downloads 

Files

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.