views:

52

answers:

4

I'm using the following function call:

var filesfound = filterSplit.SelectMany(
    filter => folder1.GetFiles(
                    filter, 
                    SearchOption.AllDirectories
    )
);  

And I'd like to put a conditional statement in there that will change SearchOption.AllDirectories to SearchOption.TopDirectoryOnly based on a certain condition (A checkbox checked or not)

Is there a way to do this? (I can't put the entire declaration into an if statement, even with an else option still declaring it, as it doesn't allow me to, saying that filesfound does not exist...)

+6  A: 

If you just want to use a conditional as an expression then use the ternary / conditional operator

m_checkBox.Checked ? SearchOptions.TopDirectoryOnly : SearchOption.AllDirectories

Complete Sample

var filesfound = filterSplit.SelectMany(filter => folder1.GetFiles(
  filter, 
  m_checkBox.Checked 
    ? SearchOptions.TopDirectoryOnly 
    : SearchOption.AllDirectories)); 

One other thing I noticed in your question is you tried to use a conditional statement block to wrap your expression. While this case can be solved without a statement there are occasions where using a statement is more natural. In those instances it's often easier to move the statement into the lambda instead of surrounding the enclosing statement.

var filesfound = filterSplit.SelectMany(filter => 
{
  if ( m_checkBox.Checked ) { 
    return folder1.GetFiles(filter, SearchOptions.TopDirectoryOnly); 
  } else {
    return folder1.GetFiles(filter, SearchOptions.AllDirectories);
  }
});
JaredPar
I'm sure you're only calling it the ternary operator to wind me up.
Jon Skeet
@Jon, I can't break the habit of calling it the ternary operator. Been doing it since college and hard to switch my thought process to conditional :)
JaredPar
thanks a lot! I knew there was a way to do this, I just couldn't remember how.
rar
+1  A: 
var filesfound = filterSplit.SelectMany(filter => folder1.GetFiles(filter, checkbox.Checked ?  SearchOption.TopDirectoryOnly : SearchOption.AllDirectories));
Kefir
+1  A: 
var filesfound = filterSplit.SelectMany(filter => 
{
    SearchOption so;
    if (checkbox.Checked)
        so = SearchOption.TopDirectoryOnly;
    else
        so = SearchOption.AllDirectories;

    return folder1.GetFiles(filter, so);
});  
gbogumil
+1  A: 

What about a good old ternary operator?

var filesfound = filterSplit.SelectMany(filter => folder1.GetFiles(filter, 
       checkBox.Checked ? SearchOptions.AllDirectories : SearchOptions.TopDirectoryOnly))
Eric