.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

One Line Lambda-Lookup list of Lambda Expressions for common scenarios

Posted By:Jean Paul       Posted Date: December 07, 2010    Points: 75    Category: LINQ    URL: http://www.dotnetspark.com  

Advantage of Lambda Expressions. In this article we will see the list some of the useful Lambda Expressions here comparing with the without-lambda approach.
 

I have observed that Lambda Expressions got good steam among developers.  It helps us in reducing lot of code and save time.

I would like to list some of the useful Lambda Expressions here comparing with the without-lambda approach.

Common Setup Code

Here the common initialization code for using the below examples are given:

List<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

Scenario Lambda Approach Traditional Approach
Descending Sort

list.OrderByDescending(i => i);

list.Sort(delegate(int x, int y)

    {

        return y.CompareTo(x);

    });

Check all numbers are less than 100

bool result = list.All(i => i < 100);

bool result = true;

foreach (int i in list)

    if (i >= 100)

        result = false;

Check any numbers are equal to 5

bool result = list.Any(i => i == 5);

bool result = false;

foreach (int i in list)

    if (i == 5)

        result = true;

Get the top 5 items in the list

var sublist = list.Take(3);

var sublist = new List<int>();

for (int i = 0; i < 5; i++)

    if (i < list.Count)

        sublist.Add(i);

Sort descending, get all numbers less than 8, take the top 5

var result = list.OrderByDescending(i => i).Where(i => i < 8).Take(5);

list.Sort(delegate(int x, int y)

{ 

    return y.CompareTo(x); 

});

 

List<int> result = new List<int>();

foreach (int i in list)

    if (i < 8)

        if (result.Count < 5)

            result.Add(i);

Summary

I think the examples above demonstrate, how complex the code will look even if you do the simple sorting and selection.

Surely Lambda Expressions is worth learning and in the long run it would give more manageable code.

Note

In the sorting scenario above, the original list is not updated, OrderBy() will be giving a sorted view of the original list.

For assigning it back to the original list we have to use the ToList() method as:

list = list.OrderByDescending(i => i).ToList<int>();


 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