Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have recently started a new job and am being forced to use VS 2005 and .NET 2.

ID: 644054 • Letter: I

Question

I have recently started a new job and am being forced to use VS 2005 and .NET 2. This has been quite painful for a number of reasons, but the one big change from VS 2005 to its successors was the introduction of LINQ and extension methods.

A common pattern that I used to follow when using enumerations was the following:

foreach(var myObject in myObjects.Where(x => x.Property == someValue)
{
    //Do some stuff
}
What I am having difficulty with is coming up with a succinct way of expressing the same statement in C# 2. The best I have come up with is the following:

foreach(MyObject myObject in myObjects)
{
    if(myObject.Property == someValue)
    {
        //Do some stuff
    }
}
Is there a more effective or efficient way of writing this code?

How would you write C# 2 code so that it can most easily be transformed into C# 5 code (we will be upgrading to VS2012/.NET 4.5 after the next release)?

Explanation / Answer

Well, you have a few interesting bits to overcome:

Lambda syntax wasn't introduced until VS 2008, so you'd have to implement using anonymous delegates.
You can't even simulate extension methods for .NET 2 with VS 2005. VS 2008 only.
Func<> and its relatives weren't introduced until .NET 3.5
The Func<> delegates are covariant on their input and contravariant on their output. Not going to have that until .NET 4, so your use may be limited.
That being said, if you grab LINQBridge, you should be able to remove the extension method syntax and use it.

EDIT

So, for grins and giggles, I just translated LINQBridge into .NET 2.0 / VS 2005. Was easy, but not terribly pleasant :) Your example foreach above would wind up looking like this after the re-do:

foreach(MyObject myObject in Enumerable.Where(myObjects, delegate(MyObject x) { return x.Property == someValue; }))
{
//Do some stuff
}
This makes me think that your non-LINQ foreach is much easier to read for the environment you're working in.