Where tips in LINQ

These might be old but as I was going through doing some code reviews and optimizations I thought I would share with the rest of the class.

Count() > 0 vs. Any

This is a bit of heated debate but as you dive in the LINQ world you'll start seeing simpler ways to write things. LINQ itself gets you away from writing loops for example (sometimes). One thing I notice in code are things like this:

if(entity.Where(some condition).Count() > 0)

When you could just write this instead:

if(entity.Any(some condition))

For me, writing *less* code is *more* important. It's a cornerstone in refactoring. Making your code more readable, more succinct. If you can scan code quicker while troubleshooting a problem or trying to figure out where to add an enhancement, all the better.

Donn Felker wrote  about the Count() vs. Any() discussion here back in 2009 and it was discussed on StackOverflow here in case you're wondering if Any() is more performant than Count() (it generally is). So my advice is use Any() to make your code potentially easier to read unless there's a performance problem.

Another simple tip for code reduction is this one.

var x = entity.Where(some condition).FirstOrDefault();

Becomes:

var x = entity.FirstOrDefault(some condition);

I know it's simple but again it's about readability. The better you can scan someone elses new code you've never seen before is less time stumbling over the syntax and more about what the intention is.

Yes, these tips are old but you would be surprised seeing new developers write new code with them and wonder why?

5 Comments

  • I agree with you. It's important to write less code that can be readable and comprehensible by other developers.

    Salvo.

  • Another simple tip for code reduction is this one.

    var x = entity.Where(some condition).FirstOrDefault();
    Becomes:

    var x = entity.FirstOrDefault(some condition);

    That was a total "no way!" moment for me. I'm switching to using that by default from now on. Thanks for the tip.

  • Using the Linq extension method Count with lambda expression will be more effective compared to the corresponding Any(lambda) method. More or less it always depends - on the ORM, on the underlying server, etc.

  • What about the performance on the 'FirstOrDefault' tip? Any significant difference?

  • @Salvo: Please note that less code doesn't always result in a readable and/or comprehensible code. There are times when less code will damage the architecture of the entire App, or times where less code accompanies more "comments", or even it results in poor performance. These (and many other) are conditions that we need to take into account. :)

Comments have been disabled for this content.