Continuing from part 1, here I will go one more step further and explain the language constructs basics in C# 3.0 which will help us in writing a LINQ query.
In C# 2.0 you can write anonymous delegate methods that helps in reducing the amount of code written. To explain this, first I will demonstrate a simple code snippet that searches for a Contact based on the FirstName field using predicates in C#2.0
1: class Contact {
2: private String _firstName;
3: /* other fields go here */
4: public String FirstName {
5: get {
6: if(_firstName != null) {
7: return _firstName;
8: }
9: }
10: set {
11: _firstName = value;
12: }
13: }
14: }
Now lets get all the contacts stored, the GetAllContacts() can also be a call to Data Access Layer to get the values
1: List <Contact> myContacts = GetAllContacts();
Next we will use System.Collection.List<T>.FindAll to search for the contact based on FirstName. The MSDN documentation has the following information on the FindAll method
Retrieves the all the elements that match the conditions defined by the specified predicate.
Syntax
C#
public List<T> FindAll ( Predicate<T> match )
The Predicate delegate that defines the conditions of the elements to search for.
A List containing all the elements that match the conditions defined by the specified predicate, if found; otherwise, an empty List.
In our example :
1: List <Contact> contact = myContacts.FindAll( new Predicate<Contact> ( FirstNameFilter ) );
2:
3: //definition for FirstNameFilter
4:
5: static bool FirstNameFilter(Contact c) {
6: c.FirstName = "Bindesh";
7: }
Lets rewrite the code using C# 2.0 Anonymous method
1: List <Contact> contact = myContacts.FindAll( delegate(Contact c) { return c.FirstName = "Bindesh"} );
1: List <Contact> contact = myContacts.FindAll( c=>c.FirstName == "Bindesh");
(input parameter) => (statement); //Called as statement lambda
(input parameter) => (expression); //Called as expression lambda
Hope this gives you a basic idea of what is lamda expression and its evolution. In my next blog I will explore more on extension methods, expression trees and queries.
catch you later ..
PingBack from http://msdnrss.thecoderblogs.com/2008/03/22/c-30-features-basics-for-linq-part-ii/