Lambda Expression Usages - some basic examples

Hi,

Continuing from my previous post in this post I will put up some examples of the places and the way we can use Lambda Expression. I will post all the examples based on the where clause of the LINQ query on arbitrary collection of integer, string.

static int[] numbers = new [] { 0,1,2,3,4,5,6,7,8,9 };

static string[] strings = new [] { "a","b","c","d","e","f","g" };

class Employee
{

      public string Name {get; set;}

      public int Salary {get; set;}

}


To filter out only those values which matches a certain condition


var Vnums = numbers.Where(int n => n > 4);

To filter out only those values from the collection of string which matches a certain condition

var v = strings. Where (s => s[0] == 'g');
 
To select only the first records that matches the criteria

var Vnums = numbers.First(int n => n > 4);

To return and anonymopus type using a Lambda

var q = strings.Select(s => new {S1 = s + “1”, s2 = s + “2”} );

Vikram


Share this post   Email it

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia