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.