Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Tip/Trick

The Elegant Art of Programming

Rate me:
Please Sign up or sign in to vote.
3.20/5 (3 votes)
15 May 2012CPOL1 min read 22K   2   20
This tip uses the elegant LINQ to solve pesky daily problems.

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:

C#
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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Guillaume Leparmentier18-May-12 9:28
Guillaume Leparmentier18-May-12 9:28 
GeneralRe: My vote of 3 Pin
Erol Esen18-May-12 10:17
Erol Esen18-May-12 10:17 
GeneralRe: My vote of 3 Pin
Guillaume Leparmentier18-May-12 10:58
Guillaume Leparmentier18-May-12 10:58 
GeneralRe: My vote of 3 Pin
Erol Esen20-May-12 13:36
Erol Esen20-May-12 13:36 
Questionyet another solution... Pin
Andreas Gieriet15-May-12 5:58
professionalAndreas Gieriet15-May-12 5:58 
GeneralRe: yet another solution... Pin
PIEBALDconsult15-May-12 8:08
mvePIEBALDconsult15-May-12 8:08 
GeneralRe: yet another solution... Pin
Andreas Gieriet15-May-12 10:25
professionalAndreas Gieriet15-May-12 10:25 
GeneralRe: yet another solution... Pin
Erol Esen15-May-12 11:18
Erol Esen15-May-12 11:18 
GeneralRe: yet another solution... Pin
PIEBALDconsult15-May-12 12:46
mvePIEBALDconsult15-May-12 12:46 
GeneralRe: yet another solution... Pin
Andreas Gieriet15-May-12 13:03
professionalAndreas Gieriet15-May-12 13:03 
GeneralRe: yet another solution... Pin
PIEBALDconsult15-May-12 14:28
mvePIEBALDconsult15-May-12 14:28 
GeneralRe: yet another solution... Pin
Andreas Gieriet15-May-12 23:40
professionalAndreas Gieriet15-May-12 23:40 
Questioneven simpler Pin
Andreas Gieriet15-May-12 5:32
professionalAndreas Gieriet15-May-12 5:32 
SuggestionDon't do that with real values (double, float, decimals)! Pin
Andreas Gieriet15-May-12 5:03
professionalAndreas Gieriet15-May-12 5:03 
GeneralRe: Don't do that with real values (double, float, decimals)! Pin
Erol Esen15-May-12 5:30
Erol Esen15-May-12 5:30 
GeneralRe: Don't do that with real values (double, float, decimals)! Pin
Andreas Gieriet15-May-12 5:43
professionalAndreas Gieriet15-May-12 5:43 
SuggestionAlternatives... Pin
Andrew Rissing15-May-12 4:42
Andrew Rissing15-May-12 4:42 
Technically, you don't need to select it prior to doing the distinct. It just adds extra overhead.

I'd probably suggest rewriting it to be something of the sort:
C#
isSame = (list.Distinct().Count() == 1);

Or even (without distinct):
C#
isSame = ((list.Count > 0) && list.All(x => x == list[0]));

Two things to be aware of (albeit I'm sure this was just a vehicle for your example):

  • Equality in floating point numbers are notoriously bad.
  • You don't handle the case when the list is empty.

GeneralRe: Alternatives... Pin
Erol Esen15-May-12 5:25
Erol Esen15-May-12 5:25 
Suggestion..or .. Pin
ednrg15-May-12 4:36
ednrg15-May-12 4:36 
GeneralRe: ..or .. Pin
delscorcho1@gmail.com17-May-12 6:22
delscorcho1@gmail.com17-May-12 6:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.