I had a typed DataTable which to sort was just something like:
DataTable.DefaultView.Sort("sortexpression");
Because the sort expression was a string I could just append both the sort field and direction in a couple of lines, regardless of how many sort options I had. Now with Linq Im clearly doing something very wrong because to do something similar I’m doing this:
this.GetSortExpressions();
if ((ViewState["SortDirection"] as string) == "ASC")
{
switch (ViewState["SortField"] as string)
{
case "LKey":
this.SortedDetails = this.Details.OrderBy(d => d.LKey);
break;
case "MName":
this.SortedDetails = this.Details.OrderBy(d => d.MaterialName);
break;
case "FMSQOH":
this.SortedDetails = this.Details.OrderBy(d => d.FMSQOH);
break;
case "CCQOH":
this.SortedDetails = this.Details.OrderBy(d => d.CCQOH);
break;
case "FMSQOHVary":
this.SortedDetails = this.Details.OrderBy(d => d.FMSQOHVary);
break;
default:
this.SortedDetails = this.Details.OrderBy(d => d.LKey);
break;
}
}
else
{
switch (ViewState["SortField"] as string)
{
case "LKey":
this.SortedDetails = this.Details.OrderByDescending(d => d.LKey);
break;
case "MName":
this.SortedDetails = this.Details.OrderByDescending(d => d.MaterialName);
break;
case "FMSQOH":
this.SortedDetails = this.Details.OrderByDescending(d => d.FMSQOH);
break;
case "CCQOH":
this.SortedDetails = this.Details.OrderByDescending(d => d.CCQOH);
break;
case "FMSQOHVary":
this.SortedDetails = this.Details.OrderByDescending(d => d.FMSQOHVary);
break;
default:
this.SortedDetails = this.Details.OrderByDescending(d => d.LKey);
break;
}
}
It’s god awful. I’m concerned about the fact that Im adding 2*n case statements for every new sort field. What is the right way please?
I have been gone through this.. what i found lastly was a generic solution that use reflection to sort a IEnumerable object.
http://zhousanfeng.wordpress.com/2009/12/01/a-generic-comparersorter-class%E8%BD%AC/
this will be how you could use it
Regards.