Introduction
One of the most rewarding experiences of computer
programming is to find more elegant ways of solving a problem. In this tip, I would like to first describe a
realistic problem. Then show a longer way of solving it (dare I say, intuitive?)
Finally show an elegant way of solving it in Microsoft LINQ.
The purpose of this tip is not to explain the details of LINQ, but show how it can be used in a simple to understand context. Reading the code should be very straightforward.
Problem
Imagine you have a list of double numbers, and we want to
know if all the numbers in the list are the same, or not.
Solution 1
A simple console application in C# would solve this problem using a flag, a for loop, and a couple of if statements:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Solution1
{
class Program
{
static void Main(string[] args)
{
List<double> myList = new List<double>();
myList.Add(1.0);
myList.Add(2.0);
myList.Add(1.0);
bool isSame = true;
double track = -1.0;
foreach (double num in myList)
{
if (track < 0.0)
{
track = num;
}
else
{
if (track != num)
{
isSame = false;
break;
}
}
}
if (isSame)
{
Console.WriteLine("All numbers are the same.");
}
else
{
Console.WriteLine("All numbers are not the same.");
}
Console.ReadKey();
}
}
}
Solution 2
Even if you have seen LINQ in action before, it's still fun to see it again:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Solution2
{
class Program
{
static void Main(string[] args)
{
List<double> myList = new List<double>();
myList.Add(1.0);
myList.Add(1.0);
myList.Add(1.0);
var query1 = (from num in myList select num).Distinct();
if (query1.Count() > 1)
{
Console.WriteLine("All numbers are not the same.");
}
else
{
Console.WriteLine("All numbers are the same.");
}
Console.ReadKey();
}
}
}
Points of Interest
While both programs do the same thing, the solution in LINQ is an order of magnitude times smaller. It focuses on the algorithm and not the loop, as Bjarne Stroustrup encourages all programmers to do so. Attached are the projects for solutions 1 and 2.