I have code like following:
switch(sort.Column)
{
case "code":
model = (sort.Direction == SortDirection.Ascending)
? model.OrderBy(x => x.code)
: model.OrderByDescending(x => x.code);
break;
case "name":
model = (sort.Direction == SortDirection.Ascending)
? model.OrderBy(x => x.name)
: model.OrderByDescending(x => x.name);
break;
..............
}
I have about 10-15 fields (like ‘code’ and ‘name’) and I do not want to copy and paste similar code with only one difference – field name.
Is there method to generalize query somehow?
You can use reflection (this assumes
codeandnameare properties; if they are public variables, you’ll have to modify accordingly):As Dunc points out in the comments below, this approach forces reflection at each step of the enumeration, and reflection is expensive as operations go. If your collection is homogeneous, you can achieve better performance by moving the reflection out of the enumeration. If your
modelcontains only elements of typeFoo, you can do the following instead:Please not that this will throw a
TargetExceptionif your collection is not homogeneous.