The purpose of this is to avoid writing a ton of if() statements.
Here is my current code:
public override List<oAccountSearchResults> SearchForAccounts(oAccountSearchCriteria searchOptions)
{
List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);
results.Sort((a1, a2) => a2.AccountNumber.CompareTo(a1.AccountNumber));
return results;
}
What I would like to do is provide a parameter which tells me which field to sort on. Then dynamically update my sort criteria without having a bunch of if() statements such as this:
public override List<oAccountSearchResults> SearchForAccounts(oAccountSearchCriteria searchOptions, string sortCriteria)
{
List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);
if (sortCriteria == "AccountNumber")
{
results.Sort((a1, a2) => a2.AccountNumber.CompareTo(a1.AccountNumber));
}
else if (sortCriteria == "FirstName")
{
results.Sort((a1, a2) => a2.FirstName.CompareTo(a1.FirstName));
}
return results;
}
I would like to do this without having about 30 if() statements for all the sortable criteria that will be available.
Any and all help will be appreciated.
EDIT WITH SOLUTION:
Thank you all for your responses.
David, your approached worked but I think that Richard's answer works a bit better.
Here is the ultimate solution that I came up with. I used David's framework for the example and Richards implementation:
using System;
using System.Collections.Generic;
namespace SortTest
{
class Program
{
static void Main(string[] args)
{
var results1 = Search(oObject => oObject.Value1);
foreach (oObject o in results1)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.WriteLine(Environment.NewLine);
var results2 = Search(oObject => oObject.Value2);
foreach (oObject o in results2)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.ReadLine();
}
public static List<oObject> Search<T>(Func<oObject, T> keyExtract) where T: IComparable
{
var results = new List<oObject>
{
new oObject {Value1 = "A 1", Value2 = "B 2"},
new oObject {Value1 = "B 1", Value2 = "A 2"}
};
results.Sort((a, b) => keyExtract(a).CompareTo(keyExtract(b)));
return results;
}
}
class oObject
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
}