Geeks With Blogs

News

Locations of visitors to this page

View ► Sanjay Uttam [sanjay.uttam@gmail.com]'s profile on LinkedIn


Add to Google Reader or Homepage




Sanjay Uttam Predominantly .NET

Just a quick tip that I found handy while doing some writing yesterday; chances are if you’ve played with LINQ you probably wrote something like this…

var outputString = from s
                   in inputString
                   where s.Length > 1
                   select s;
 
//Do some stuff with outputString in your method...

Code like the above will work perfectly well if what you’re going to work with your implicit variable, outputString, within the body of the same method.  But, as it stands, you can’t return outputString, or any implicit variable from your method.  Try it, I dare you.  At this point, you’re probably thinking “Wait, can’t I just do a outputString.ToList() or .ToArray() and return that?  Yes – you can.  The catch with doing that, though, is that your LINQ expression is going to be evaluated right there and then.  This might be fine for you, or it might not – but you should be aware of the deferred query execution model that LINQ embraces. 

In any case, the easy way out of this assuming you’d prefer to defer execution until you enumerate is actually very straightforward….You can simply return an IEnumerable<T>.  So, something like…

static IEnumerable<string> DoLinqStuff(string[] inputString)
{
    //You can do this and return an IEnumerable<string>
    IEnumerable<string> outputString =  from s
                                        in inputString
                                        where s.Length > 1
                                        select s;
 
    return outputString;
}

That way, you can do the following to leverage your LINQ expression in an external method while leaving the deferred execution model in-tact…

//Remember this isn't evaluated yet...
IEnumerable<string> myReturnedStuff = DoLinqStuff(myStrings);
 
//It's getting evaluated now...
foreach (string s in myReturnedStuff) {
    Console.WriteLine(s);
}

Or if you want to be a bit more concise about it…

//Same thing but slightly less code...
foreach (string s in DoLinqStuff(myStrings)){
    Console.WriteLine(s);
}

Okay, so it wasn’t exactly rocket-science but I figure it may be helpful. 


kick it on DotNetKicks.com

 

Share this post :

 

Technorati Tags: ,,,
Posted on Friday, September 11, 2009 5:09 PM | Back to top

Copyright © Sanjay Uttam | Powered by: GeeksWithBlogs.net