Linq, Lambda Expressions and Predicate Delegates
I have recently been giving the opportunity to play around a bit more with Linq and while playing around with that I have run into the related topics of Lambda Expressions and Predicates. This post will be broken up into 3 sections (can we guess what they are?) and will just briefly provide an over view for each.Linq
Linq stands for language-integrated query, and it allows you to query your data sets in code instead of heading back to the database in order to get a subset, and without having to loop through code. The syntax is very similar to SQL.For example lets say I had a list of people, and I wanted to pull back everyone who lived in Richmond. Previously I would have to go back to the database and reselect my list of people or maybe loop through the list and do it that way. But using Linq I can do this much easier.
List<People> myPeeps = new List<People>();As you can see this syntax is very similar syntax to SQL. You can now take the results and bind them a control, or do any sort of computations on it.
//Fill list
var results = from p in myPeeps
where p.Location= "Richmond"
orderby p.Name
select p;
Lambda Expressions
Lambda Expressions are defined by MSDN as "...an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types."So what exactly that means I'm not to sure, but it makes it real easy to filter things out inline and simplifies the above Linq query a bit. Using the same situation above the query changes to
myPeeps.Where(p => p.Location== "Richmond");Pretty simple no? It doesn't have all the same power as Linq since you can really order or use multiple criteria and the like, but it is very simple and easy to use.
Predicates Delegates
Predicates are defined as "...the method that defines a set of criteria and determines whether the specified object meets those criteria." What that means is that you can define a function that returns a boolean to evaluate if your item in a list meets certain criteria. Again using the above example, I define the actual predicate delegate.
And once that is done, I just pass the predicate into the select clause on my list.
private bool IsRichmonder(People p) {
return p.Text == "Richmond";
}
myPeeps.Select(IsRichmonder);
Summary
All of these examples have been pretty simple, but I hope you can see the power of all of these methods when properly leveraged.I relied on ScottGu's articles to learn about these and to write this post
Labels: .NET
posted by Tom Becker at
6/12/2009
![]()

0 Comments:
Post a Comment
<< Home