So today at work I had to come up with a method that would give me a listing of something from a collection. If the listing didn't exist, I wanted the listing to be initialized and automatically added to the list.
Let's look at my pathetic first attempt.
private Listing GetListing(List<Listing> cars, string name)
{
Listing listing = null;
IEnumerable<Listing> results = cars.Where(i => i.Name == name);
//if map doesn't exist create it
if (results.Count() == 0)
{
listing = new Listing()
{
Name = name,
AdditionalData = new List<Data>()
};
cars.Add(listing);
}
else
{
//If we originally did this, it would throw an
//exception when there are no matches found.
//That's why this part is in the else block.
listing = results.First();
}
return listing;
}
As you can see, I tried to get fancy and use Linq. I found, through testing, that the method .First() would throw an exception if there were no results. There were other methods, but for some reason I just couldn't think of the right method.
So then I threw my hands in the air and figured it'd be shorter to just write a method without Linq and that I was just over complicating it.