Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to order by multiple columns using Lambas and LINQ in C#

DZone's Guide to

How to order by multiple columns using Lambas and LINQ in C#

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

Today, I was required to order a list of records based on a Name and then ID. A simple one, but I did spend some time on how to do it with Lambda Expression in C#. C# provides the OrderBy, OrderByDescending, ThenBy, ThenByDescending. You can use them in your lambda expression to order the records as per your requirement.

Assuming your list is “Phones” and contains the following data

public class Phone
{
       public int ID { get; set; }
       public string Name { get; set; }
}

public class Phones : List
{
        public Phones()
        {
            Add(new Phone { ID = 1, Name = "Windows Phone 7" });
            Add(new Phone { ID = 5, Name = "iPhone" });
            Add(new Phone { ID = 2, Name = "Windows Phone 7" });
            Add(new Phone { ID = 3, Name = "Windows Mobile 6.1" });
            Add(new Phone { ID = 6, Name = "Android" });
            Add(new Phone { ID = 10, Name = "BlackBerry" });
        }
}

If you were to use LINQ Query , the query will look like the one below

dataGridView1.DataSource = (from m in new Phones()
                                       orderby m.Name, m.ID
                                       select m).ToList();

Simple isn’t it ? It very simple using Lamba expression too. Your Lambda’s expression for the above LINQ query will look like the one below

dataGridView1.DataSource = new Phones().OrderByDescending(a => a.Name).ThenByDescending(a => a.ID).ToList();

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
dotnet ,how-to ,microsoft ,tools ,c# ,linq ,data

Published at DZone with permission of Senthil Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}