Possible Duplicate:
Dynamic LINQ OrderBy
switch (sort) {
case "Title":
queryResults = queryResults.OrderBy(r => r.Title);
break;
default:
queryResults = queryResults.OrderBy(r => r.LastName);
break;
Is there any way I can get rid of the switch block above?
Can I do some thing like:
queryResults = queryResults.OrderBy(r => r."sort");
or
queryResults = queryResults.OrderBy(r => r.sort);
Don't Repeat Yourself (DRY): Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.
Therefore nested switch statements should be avoided. Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.
The main differences between the two are: The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed.
Switch case is not a bad syntax, but its usage in some cases categorizes it under code smell. It is considered a smell, if it is being used in OOPS. Thus, Switch case should be used very carefully.
If you wanted to do this completely dynamic, you could use some reflection (simple example):
string prop = "Title";
var q = queryResults.OrderBy(x => x.GetType().GetProperty(prop).GetValue(x, null));
I wouldn't consider this the nicest solution in any case though. Whether this really makes sense for you depends on where you get the property name from (if you get it from reflection, too, or not) and how many properties there are.
This should do it
queryResults = queryResults.OrderBy(r => sort == "Title" ? r.Title : r.LastName)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With