Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practices for dealing with LINQ statements that result in empty sequences and the like?
    text
    copied!<p>...I'm a little confused, or unsure about how to deal with errors that arise from LINQ statements. I just love being able to pull one or more items from a collection, based on some criteria... with a <em>single</em> line of code. That's pretty awesome.</p> <p>But where I'm torn is with the error handling, or the boundary condition checking. If I want to retrieve an item using First(), and <em>no item</em> satisfies my query, an exception gets thrown. That's a bit of a bummer because now I have to wrap every LINQ statement with a separate try/catch block. To me, the code starts to look a little messy with all of this, especially since I end up having to declare variables outside of the try/catch block so I can use their (null) values later (which were set to null in the catch block).</p> <p>Does anyone here understand my predicament? If I have to wrap every LINQ statement in try/catch blocks, I will, because it's still a hell of a lot better than writing all sorts of for loops to accomplish the same thing. But there <em>must</em> be a better way, right? :) I'd like to hear what everyone else here does in this situation.</p> <p>** UPDATE **</p> <p>Thanks for the answers, guys, they have been very helpful. One other thing I also was going to bring up, along the "one-lineness" of LINQ, is that if I want to get some .some_value.some_value.some_other_value, if I adopt an approach where I have to check for a Nullable, I have to do it from the most basic LINQ query first, then I can query for the result's property that I'm looking for. I guess there's no way around this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload