posts - 217, comments - 218, trackbacks - 239

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes (acquired by LiveUniverse) www.pageflakes.com
and most recently created SmartCodeGenerator

My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

LINQ - "Where" Extension Method

Here is simple LINQ example where I have used Extension methods "Where", to select the participants whose score is greater than 80.

var participants =
Competition.GetParticipants()
.Where(participant=> participant.Score > 80)
.OrderByDescending(participant => parricipant.Score)
.Select(participant => new { participant.Id,
Name=participant.Name });


Note: here we are sending a Lamda expression (participant=>participant.Score>80) as parameter of the "Where" extension method. Ever wondered how this extension method is declared and what is happening inside?

Here you go:

public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Boolean> predicate)
{
  foreach (TSource element in source)
  {
    if (predicate(element))
    yield return element;
  }
}

I am sure you noticed the "this" word in the above code snippet, that's  how extension methods are declared, simply adding a "this" word turns your method into an Extension Method.

Print | posted on Monday, January 28, 2008 1:38 AM |

Feedback

Gravatar

# re: LINQ - "Where" Extension Method

I think there is a typo in this post:
".Where(participant=> participants.Score > 80)"
should be participant in both cases.
Thanks
2/23/2008 9:48 AM | Sam Piper
Gravatar

# re: LINQ - "Where" Extension Method

Very useful !! Thanks :)
6/3/2008 3:56 AM | tom-i
Gravatar

# re: LINQ - "Where" Extension Method

great, it's easy and useful! :)
7/29/2008 4:58 AM | asp.net c#
Gravatar

# re: LINQ - "Where" Extension Method

Is there a way we can build our where condition dynamically and ammend later lke,

from u in db.tblUser
where u.FirstName.StartsWith(txtFirstName)

if (txtLastName.Text != String.Empty)
where u.LastName.StartsWith(txtLastName)

where u.Sex == Convert.ToInt16(cboSex.SelectedValue)

How can I add these 3 where conditions to my original query.
7/29/2008 5:04 PM | nalaka
Gravatar

# re: LINQ - "Where" Extension Method

simple and usefull. Great :)
9/4/2008 1:08 AM | Guf

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 3 and 5 and type the answer here:

Powered by: