What was big and clunky is now small with LINQ

Don’t tell anyone but I’ve realized there are people smarter than me.  I’ve been slow like most getting up to speed with the new technologies, one being LINQ.  The demos I’ve seen of it have always been SQL based.  SQL and myself never really liked one another so LINQ has always been something I gave the evil eye to.  I knew it was powerful, just didn’t realize how wide spread it actually is!

So I wanted to grab a few unique images from a directory on a computer then out put them to a user.  Now the code to do this was big and could be slow but there are algorithms out there to make this faster.  Now what if there was a way to have this magically be done for me?

Old Code:

private string getUniqueFile(string[] files, 
    string currentMapPath, params string[] usedNames)
{
    string randomName = "";

    for (int i = usedNames.Length - 1; i >= 0; i--)
    {
        if (i == usedNames.Length - 1)
            randomName = getRandomFile(files, currentMapPath);

        if (randomName == usedNames[i])
            i = usedNames.Length;
    }

    return randomName;
}

Random random = new Random((int)DateTime.Now.Ticks);
private string getRandomFile(string[] files, string currentMapPath)
{
    return files[random.Next(files.Length)]
        .Remove(0, currentMapPath.Length + 1)
        .Replace("\\", "/");
}

New Code with LINQ:

private string getUniqueFile(IEnumerable<string> files, 
    string currentMapPath, params string[] usedNames)
{
    return getRandomFile(files.Except(usedNames), currentMapPath);
}

Random random = new Random((int)DateTime.Now.Ticks);
private string getRandomFile(IEnumerable<string> files, string currentMapPath)
{
    return files.ElementAt(random.Next(files.Count()))
        .Remove(0, currentMapPath.Length + 1)
        .Replace("\\", "/");
}
 

So the big thing we see here is how small the new code is.  Also how much more readable it is.  Also someone far smarter than me created the algorithm for the Except method.

As you can see, LINQ isn’t just SQL like styles, it is built into collections so use it!  It will make your life far easier.

Matt Newman Dec 17, 2008 @ 2:25 PM

# re: What was big and clunky is now small with LINQ
One caveat though with Linq, it doesn't always work with WPF. It'll do basic binding but if you want to do WPF sorting, grouping, or filtering Linq queries don't always work.

Fortunately though... BindableLinq http://www.codeplex.com/bindablelinq

Ross Dargan Dec 17, 2008 @ 3:07 PM

# re: What was big and clunky is now small with LINQ
The best part of this code is you have said what you want to do not how to do it which means optimisations later on (like multi threading etc) will improve the performance of your code without you making any changes - I would expect .net to be making more use of this sort of thing in .net 4 and 5!

Ross

Post a Comment

Please add 8 and 2 and type the answer here: