GravatarBen Ramey's Blog
Scripture, programming problems, solutions and stories.

Enumerables in C#

Since starting my job in September 2020 at Faithlife, one of the most eye-opening realizations for me was how ignorant I was of how, when and why to use the various C# enumerable types and interfaces. C# gives you many of them. It's probably no surprise that they each have a place in your code! It probably should also be no surprise that misusing them can really put a dent in your code's efficiency.

I've learned a lot since then from the fantastic developers surrounding me at Faithlife. So, I wanted to start a blog series on the various enumerable types and interfaces and give some guidance on when and how to use them well. I'm also starting this series to push my knowledge on the subject further. So, please interact and comment with your own recommendations and corrections for me!

To start us off, here's an example of the type of thing I used to do quite often:

List<Driver> drivers = GetDriversFromDb();
List<Car> cars = GetCarsFromDb();
var garages = new List<Garage>();

foreach(var driver in drivers)
{
    if (cars.Any(c => c.OwnerId == driver.Id))
    {
        garages.Add(new Garage(driver, cars.Where(c => c.OwnerId == driver.Id)));
    }
}

Doing things like this is not smart and it doesn't take advantage of the enumerables that C# gives you to handle scenarios like this (and many others) much more efficiently.

I'm sure you can see why the above code is not great. But, if you're new to C# (or like me when I was writing stuff like that and just hadn't put too much thought into using enumerable types well) then you should know that the problem with that code is that you loop through the entire cars list for every iteration through the drivers foreach loop.

Is there a better way? There sure is! Keep tabs on this series as I go through C#'s enumerables and you'll soon know how to solve a simple problem (and many others!) like the one above much more efficiently.

To view the entire series, you can use the tag "enumerables".

See comments