On a related note to a previous entry the new .NET languages seem to be finding their feet. It’s not too outrageous to say that the original version of C# was a fairly standard OO language with few surprises. Now, however, C# in particular is becoming a mature language with some very distinctive features.
Let’s compare some older code with the new edition of C#. First, let’s see how we searched arrays:
public void LegacyQuery() { int[] numbers = { 2, 5, 28, 31, 17, 16, 42 };foreach (int number in numbers) { if (number < 20) { Console.Write("{0} ", number); } } Console.WriteLine(); }
Now we have LINQ, we can do it another way (I’m assuming readers have a little knowledge of LINQ, but even if you don’t, it’s the contrast I’m trying to get across):
public void LinqQuery() { int[] numbers = { 2, 5, 28, 31, 17, 16, 42 };var numsQuery = from n in numbers where n < 20 select n;foreach (var x in numsQuery) Console.Write("{0} ", x); Console.WriteLine(); }
It looks a bit different although it’s not necessarily more compact. However, this simple example doesn’t demonstrate how much LINQ adds. Let’s try and sort the numbers less than 20 (in other words, we’re doing something with the data):
public void LegacyQuery() { int[] numbers = { 2, 5, 28, 31, 17, 16, 42 }; ArrayList foundNumbers = new ArrayList();foreach (int number in numbers) { if (number < 20) { foundNumbers.Add(number); } }foundNumbers.Sort(); foreach (int number in foundNumbers) { Console.Write("{0} ", number); } Console.WriteLine(); }
Here I’m just collecting the numbers together and sorting them, before display. LINQ does it much more efficiently:
public void LinqQuery() { int[] numbers = { 2, 5, 28, 31, 17, 16, 42 };var numsQuery = from n in numbers where n < 20 orderby n ascending select n;foreach (var x in numsQuery) Console.Write("{0} ", x); Console.WriteLine(); }
Here we have a single extra line of LINQ query to do the work of the foreach we saw in the traditional example. While this is a good example of what LINQ can do, it is also a good example of how changed C# is from its original form and how it has gained its own distinctive character.
