TacoMakerMan TacoMakerMan - 3 months ago 9
C# Question

Using a variable to determine sorting type of files in a directory

I have a directory of files selected by the user and I need to sort the files inside the directory based on the user's choice. So a form is meant to allow the user to select what to sort the files by from a drop down menu, but the problem is, I need to use the variable in place of the "Name, or LastWriteTime" in the code:

var sortedFiles = new DirectoryInfo(selectedPath)
.GetFiles(fileTypeTextBox.Text, SearchOption.AllDirectories)
.OrderBy(f => f."Variable Based On Selected Index of Drop Down")
.ToList();


It's hard to explain what I want for lack of knowledge on terminology but hopefully you can understand, what I mean.

Also, I am doing this in Visual Studio Express 2013, in C#

Answer

You could use if/else statements. e.g.

if(dropdown1.value == name){
    .GetFiles(fileTypeTextBox.Text, SearchOption.AllDirectories)
                      .OrderBy(f => f.Name)
                      .ToList();
}
else if(dropdown1.value == Created){
    .GetFiles(fileTypeTextBox.Text, SearchOption.AllDirectories)
                      .OrderBy(f => f.CreationTime)
                      .ToList();
}

etc.

Is that what you were asking?