Contents tagged with LINQ

  • 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?