Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload