Should I use two “where” clauses or “&&” in my LINQ query?

后端 未结 4 791
[愿得一人]
[愿得一人] 2020-11-29 03:09

When writing a LINQ query with multiple \"and\" conditions, should I write a single where clause containing && or multiple where

相关标签:
4条回答
  • 2020-11-29 03:38

    The performance issue only applies to memory based collections ... Linq to SQL generates expression trees that defer execution. More Details here:

    Multiple WHERE Clauses with LINQ extension methods

    0 讨论(0)
  • 2020-11-29 03:45

    This is mostly a personal style issue. Personally, as long as the where clause fits on one line, I group the clauses.

    Using multiple wheres will tend to be less performant because it requires an extra delegate invocation for every element that makes it that far. However it's likely to be an insignificant issue and should only be considered if a profiler shows it to be a problem.

    0 讨论(0)
  • 2020-11-29 03:53

    Like others have suggested, it's more of a personal preference. I like the use of && as it's more readable and mimics the syntax of other mainstream languages.

    0 讨论(0)
  • 2020-11-29 03:55

    I personally would always go with the && vs. two where clauses whenever it doesn't make the statement unintelligible.

    In your case, it probably won't be noticeble at all, but having 2 where clauses definitely will have a performance impact if you have a large collection, and if you use all of the results from this query. For example, if you call .Count() on the results, or iterate through the entire list, the first where clause will run, creating a new IEnumerable that will be completely enumerated again, with a second delegate.

    Chaining the 2 clauses together causes the query to form a single delegate that gets run as the collection is enumerated. This results in one enumeration through the collection and one call to the delegate each time a result is returned.

    If you split them, things change. As your first where clause enumerates through the original collection, the second where clause enumerates it's results. This causes, potentially (worst case), 2 full enumerations through your collection and 2 delegates called per member, which could mean this statement (theoretically) could take 2x the runtime speed.

    If you do decide to use 2 where clauses, placing the more restrictive clause first will help quite a bit, since the second where clause is only run on the elements that pass the first one.

    Now, in your case, this won't matter. On a large collection, it could. As a general rule of thumb, I go for:

    1) Readability and maintainability

    2) Performance

    In this case, I think both options are equally maintainable, so I'd go for the more performant option.

    0 讨论(0)
提交回复
热议问题