#### C# Sort and OrderBy comparison

Total Post:128

Points:898

2912  View(s)
Ratings:
Rate this:

I can sort a list using Sort or OrderBy. Which one is faster? Are both working on same algorithm?

`List<Person> persons = new List<Person>();persons.Add(new Person("P005","Janson"));persons.Add(new Person("P002","Aravind"));persons.Add(new Person("P007","Kazhal"));`

1.

persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));

2.

`var query = persons.OrderBy(n => n.Name, new NameComparer());class NameComparer : IComparer<string>{    public int Compare(string x,string y)    {      return  string.Compare(x, y, true);    }}`
1. ##### Re: C# Sort and OrderBy comparison

Hi Ashish,

Try this:

`class Program{    class NameComparer : IComparer<string>    {        public int Compare(string x, string y)        {            return string.Compare(x, y, true);        }    }    class Person    {        public Person(string id, string name)        {            Id = id;            Name = name;        }        public string Id { get; set; }        public string Name { get; set; }    }    static void Main()    {        List<Person> persons = new List<Person>();        persons.Add(new Person("P005", "Janson"));        persons.Add(new Person("P002", "Aravind"));        persons.Add(new Person("P007", "Kazhal"));        Sort(persons);        OrderBy(persons);        const int COUNT = 1000000;        Stopwatch watch = Stopwatch.StartNew();        for (int i = 0; i < COUNT; i++)        {            Sort(persons);        }        watch.Stop();        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);        watch = Stopwatch.StartNew();        for (int i = 0; i < COUNT; i++)        {            OrderBy(persons);        }        watch.Stop();        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);    }    static void Sort(List<Person> list)    {        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));    }    static void OrderBy(List<Person> list)    {        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();    }}`

On my computer when compiled in Release mode this program prints:

Sort: 1162ms

OrderBy: 1269ms

Modified On Apr-04-2018 04:07:12 AM

#### CONTACT INFO

10-B Taskand Marg, Near Patrika Chauraha, Civil Lines, Prayagraj, UP, India-211001.
contact@mindstick.com
91-532-2400505

969-G Edgewater Blvd,Suite
793 Foster City-94404, CA (USA)
+1-650-242-0133