Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid switch case -linq [duplicate]

Tags:

c#

.net

linq

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);
like image 849
Kuttan Sujith Avatar asked May 22 '12 12:05

Kuttan Sujith


People also ask

How do I stop duplicating codes?

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.

How do you stop a nested switch?

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.

Can switch case replace if-else?

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.

Are switch cases a code smell?

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.


2 Answers

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.

like image 175
Botz3000 Avatar answered Sep 29 '22 13:09

Botz3000


This should do it

queryResults = queryResults.OrderBy(r => sort == "Title" ? r.Title : r.LastName)
like image 45
Jan Aagaard Avatar answered Sep 29 '22 13:09

Jan Aagaard