tags:

views:

84

answers:

3

Given the following two cases, which one is preferable (If they're both bad, doing it a completely different way is an option too)?

Convert.ToInt32 called in Where:

 var items = GetItems();
 if (aDropDownList.SelectedIndex > 0) 
 {
     items = items.Where(x => 
             x.IntProperty == Convert.ToInt32(aDropDownList.SelectedValue));
 }

Convert.ToInt32 called before Where:

var items = GetItems();
 if (aDropDownList.SelectedIndex > 0) 
 {
     int selectedDropDownValue = Convert.ToInt32(aDropDownList.SelectedValue);
     items = items.Where(x => x.IntProperty == selectedDropDownValue);
 }
+2  A: 

I would prefer the second. It does only one conversion, instead of many.

But unless this is a performance-critical piece of code (unlikely; it seems like GUI code), you won't notice a difference.

Thomas
It is, as you guessed (dropdown's a giveaway) GUI code - however, adding the conversion before is that hard, and I'd like to do things the same way throughout the code, so I'm leaning strongly towards the second case as well.
jball
+2  A: 

The only difference I can see is how the compiler would generate the lambda. In the second version, the value is captured and not referenced, and this will have an effect in a multithreaded environment.

codekaizen
Ah - but the capture is on this thread, so it is safe. In the first example, though, the dropdown may change value halfway through the filtering.
David B
@David B - Right, in this case it is, but not in the general case.
codekaizen
+3  A: 

Both of these have a flaw -

You're calling .Where(...) on the collection, but doing nothing with the results. This will have no effect whatsoever, since Where does not change the original collection - it returns a new IEnumerable<T> of items that match the predicate.

That being said, I'd prefer the second option- In the first option, the Convert.ToInt32 call will be run once for each element in your collection. In a small collection, this may not matter, but as the collection gets larger, it will get slower.

You may or may not notice that difference in this situation, but it's (IMO) a good practice to declare your variables prior to using a LINQ statement. I often see situations where people assume LINQ is slow merely because they're doing expensive calculations within their predicates. In this case, your method is relatively fast, so it probably will not matter, but as a practice, it's a good habit to follow the second pattern.

Reed Copsey
(I've added in the assignment of the `Where()` results to my examples in the question) I was leaning toward the second case, but I wasn't sure if it was unneccesary, and I know concise code is valued too...
jball
It's not "necessary" - both compile and function fine. The second case is more efficient, which may or may not matter. In general, though, I personally try to practice efficent coding patterns always, and then only optimize further when there is a measured problem.
Reed Copsey