.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expressions Extension Method 12 - OrderBy() and OrderByDescending()

Posted By:Jean Paul       Posted Date: May 21, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

OrderBy() and OrderByDescending() Extension methods explained
 

The OrderBy () method is used to sort the element in an IEnumerable.

This method will take a generic argument.  On calling the method it operates on the IEnumerable returns sorted IEnumerable items.

Example

Consider the following classes where List of integers  are created.

private void InitData()

{

    // Set data

    _list.Add(1);

    _list.Add(2);

    _list.Add(3);

    _list.Add(4);

    _list.Add(5);

    _list.Add(6);

}

 

We are calling the OrderBy() method on the list:

private void OrderByButton_Click(object sender, EventArgs e)

{

    var result = _list.OrderBy(i => i);

 

    foreach (int i in result)

        MessageBox.Show(i.ToString());

}

 

The output will be the sorted list:

1

2                                                            

3

4

5

6

 

Note

We should not related OrderBy() with the Sort() method.  The Sort() will be operating on the list and modifying the list after sorting.  But here OrderBy() just operates on the IEnumerable and returns another IEnumerable.  Here the original list won't get affected.

Extension Method Snapshot

The visual studio extension method snap shot is given below for OrderBy()

OrderByDescending()

The OrderByDescending () method is used to sort the element in an IEnumerable in the reverse order.

This method will take a generic argument.  On calling the method it operates on the IEnumerable returns descending sorted IEnumerable items.

Example

Consider the following classes where List of integers  are created.

private void InitData()

{

    // Set data

    _list.Add(1);

    _list.Add(2);

    _list.Add(3);

    _list.Add(4);

    _list.Add(5);

    _list.Add(6);

}

 

We are calling the OrderByDescending () method on the list:

private void OrderByDescendingButton_Click(object sender, EventArgs e)

{

    var result = _list.OrderByDescending(i => i);

 

    foreach (int i in result)

        MessageBox.Show(i.ToString());

}

 

The output will be the sorted list:

6

5

4

3

2

1

 

Extension Method Snapshot

The visual studio extension method snap shot is given below for OrderByDescending()


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend