Secret ingredients to quality software

SSW Foursquare

Do you use the filtering parameter in LINQ methods?

Last updated by Bryden Oliver on 24 Dec 2021 12:09 am (5 months ago) See History

Many LINQ methods like Count, First and so on include an optional filter parameter. It's normally much more readable to use this than add an extra call to Where

.Where(x => x < 5).Count()
.Where(x => x < 5).FirstOrDefault()

Figure: Bad example - More code that requires extra thought to understand.

.Count(x => x < 5)
.FirstOrDefault(x => x < 5)

Figure: Good example - Shorter and easier to read.

Bryden OliverBryden Oliver

We open source. Powered by GitHub