I'm reviewing a piece of code I wrote not too long ago, and I just hate the way I handled the sorting - I'm wondering if anyone might be able to show me a better way.
I have a class, Holding
, which contains some information. I have another class, HoldingsList
, which contains a List<Holding>
member. I also have an enum, PortfolioSheetMapping
, which has ~40 or so elements.
It sort of looks like this:
public class Holding
{
public ProductInfo Product {get;set;}
// ... various properties & methods ...
}
public class ProductInfo
{
// .. various properties, methods...
}
public class HoldingsList
{
public List<Holding> Holdings {get;set;}
// ... more code ...
}
public enum PortfolioSheetMapping
{
Unmapped = 0,
Symbol,
Quantitiy,
Price,
// ... more elements ...
}
I have a method which can invoke the List to be sorted depending on which enumeration the user selects. The method uses a mondo switch statement that has over 40 cases (ugh!).
A short snippet below illustrates the code:
if (frm.SelectedSortColumn.IsBaseColumn)
{
switch (frm.SelectedSortColumn.BaseColumn)
{
case PortfolioSheetMapping.IssueId:
if (frm.SortAscending)
{
// here I'm sorting the Holding instance's
// Product.IssueId property values...
// this is the pattern I'm using in the switch...
pf.Holdings = pf.Holdings.OrderBy
(c => c.Product.IssueId).ToList();
}
else
{
pf.Holdings = pf.Holdings.OrderByDescending
(c => c.Product.IssueId).ToList();
}
break;
case PortfolioSheetMapping.MarketId:
if (frm.SortAscending)
{
pf.Holdings = pf.Holdings.OrderBy
(c => c.Product.MarketId).ToList();
}
else
{
pf.Holdings = pf.Holdings.OrderByDescending
(c => c.Product.MarketId).ToList();
}
break;
case PortfolioSheetMapping.Symbol:
if (frm.SortAscending)
{
pf.Holdings = pf.Holdings.OrderBy
(c => c.Symbol).ToList();
}
else
{
pf.Holdings = pf.Holdings.OrderByDescending
(c => c.Symbol).ToList();
}
break;
// ... more code ....
My problem is with the switch statement. The switch
is tightly bound to the PortfolioSheetMapping
enum, which can change tomorrow or the next day. Each time it changes, I'm going to have to revisit this switch statement, and add yet another case
block to it. I'm just afraid that eventually this switch statement will grow so big that it is utterly unmanageable.
Can someone tell me if there's a better way to sort my list?