C# and lambda

  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Well it has been a while and I have been working with some really cool stuff lately.

I thought I would share this handy little tid bit of info to make your life easier in .NET specifically C#.

How many times have you looped through a list looking for matching class properties and added them to another list to display them? Well I know I have done it way to many times so when I started using LINQ and lambda expressions I got really excited!

Ok so without further a do lets go.

Say we have a base class

Code: [ Select ]
public class Person{
 public String FirstName{get;set;}
 public String LastName{get;set;}
 public String Email{get;set;}
}
  1. public class Person{
  2.  public String FirstName{get;set;}
  3.  public String LastName{get;set;}
  4.  public String Email{get;set;}
  5. }


Now given a method that populates a list of Person objects
Code: [ Select ]
var myList = new List<Person>();

for(int i = 0; i < 10; i++){
myList.Add(
 //Excuse the concatination, prefered method is String.Format
 new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com"};
)
}
  1. var myList = new List<Person>();
  2. for(int i = 0; i < 10; i++){
  3. myList.Add(
  4.  //Excuse the concatination, prefered method is String.Format
  5.  new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com"};
  6. )
  7. }


Now we have a list of Person with 10 entries. Now if we wanted to find the entry with the first name "Name 1" you would traditionally loop through the list till you matched the name. Something like

Code: [ Select ]
var myPerson = null;
foreach(var person in myList){
 if(myList.FirstName.Equals("Name 1")){
  myPerson = person;
  break;
 }
}
  1. var myPerson = null;
  2. foreach(var person in myList){
  3.  if(myList.FirstName.Equals("Name 1")){
  4.   myPerson = person;
  5.   break;
  6.  }
  7. }


Man that can get annoying. So MS has provided us with a handy set of extension method in the LINQ library. To include it in your cs file you simply reference the namespace System.Linq

Code: [ Select ]
using System.Linq;


Now to achieve the same thing as the foreach loop we simply go
Code: [ Select ]
//The first or default method returns null if it doesn't find a match, First() will throw an exception if no
//matching objects are found
var myPerson = myList.FirstOrDefault(person => person.FirstName.Equals("Name 1"));
  1. //The first or default method returns null if it doesn't find a match, First() will throw an exception if no
  2. //matching objects are found
  3. var myPerson = myList.FirstOrDefault(person => person.FirstName.Equals("Name 1"));


Now that is neat!
We can also query lists from the list
Code: [ Select ]
//Obviously this will return all ten results but illustrates the purpose
var myNewList = myList.Where(person => person.FirstName.StartsWith("Name "));
  1. //Obviously this will return all ten results but illustrates the purpose
  2. var myNewList = myList.Where(person => person.FirstName.StartsWith("Name "));


Cool huh? But this is only the beginning! Say we add another property to person.
Code: [ Select ]
public class Person{
 public String FirstName{get;set;}
 public String LastName{get;set;}
 public String Email{get;set;}
 public int Salary {get;set;} //yes I know, float float float -> keeping it simple
}
  1. public class Person{
  2.  public String FirstName{get;set;}
  3.  public String LastName{get;set;}
  4.  public String Email{get;set;}
  5.  public int Salary {get;set;} //yes I know, float float float -> keeping it simple
  6. }


and we populate it with
Code: [ Select ]
var myList = new List<Person>();
Random random = new Random();
int randomNumber = random.Next(0, 100);

for(int i = 0; i < 10; i++){
myList.Add(
 //Excuse the concatination, prefered method is String.Format
 var salary = random.Next() * 1;
 new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com", Salary = salary};
)
}
  1. var myList = new List<Person>();
  2. Random random = new Random();
  3. int randomNumber = random.Next(0, 100);
  4. for(int i = 0; i < 10; i++){
  5. myList.Add(
  6.  //Excuse the concatination, prefered method is String.Format
  7.  var salary = random.Next() * 1;
  8.  new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com", Salary = salary};
  9. )
  10. }


And we want to find the total cost of our List of Persons
Code: [ Select ]
var total = myList.Sum(person => person.Salary);

Or we want to find the average of all the salaries
Code: [ Select ]
var avg = myList.Avg(person => person.Salary);


Now I don't care who you are, that is cool.It extends far further than that so I recommend having a look at it!

For more info check out
Lambda expressions:
http://msdn.microsoft.com/en-us/library/bb397687.aspx

Linq
http://msdn.microsoft.com/en-us/netframework/aa904594

Enjoy!
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

Post Information

  • Total Posts in this topic: 1 post
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 2 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.