Note that there are some explanatory texts on larger screens.

plurals
  1. POSort one List<> based on another
    text
    copied!<p>Say I have</p> <pre><code>List&lt;int&gt; ages = new List&lt;int&gt;() { 8, 5, 3, 9, 2, 1, 7 }; List&lt;int&gt; marks = new List&lt;int&gt;() { 12, 17, 08, 15, 19, 02, 11 }; </code></pre> <p>I can sort my <code>marks</code> by <code>ages</code> like this:</p> <pre><code>while (true) { bool swapped = false; for (int i = 0; i &lt; ages.Count - 1; i++) if (ages[i] &gt; ages[i + 1]) { int tmp = ages[i]; ages[i] = ages[i + 1]; ages[i + 1] = tmp; tmp = marks[i]; marks[i] = marks[i + 1]; marks[i + 1] = tmp; swapped = true; } if (!swapped) break; } </code></pre> <p>Now I want to put this into a function that accepts any two lists. The first parameter will be the reference list, the numerical or comparable list. The second parameter will be the list containing the data.</p> <p>For example:</p> <pre><code>public static void Sort&lt;T&gt;(List&lt;T&gt; RefList, List&lt;T&gt; DataList) { // sorting logic here... } </code></pre> <p>There are a few problems:</p> <p>First of all, <code>T</code> is almost certainly not the same type in <code>RefList</code> and <code>DataList</code>. RefList might be dates, integers, or doubles; whereas DataList is free to be absolutely anything. I need to be able to receive two, arbitrary generic types.</p> <p>Secondly, I cannot seem to use the <code>&gt;</code> operator with the <code>T</code> in this line:</p> <pre><code>if (ages[i] &gt; ages[i + 1]) </code></pre> <p>Perhaps my whole approach is wrong.</p> <p>By the way, I have read responses to similar questions that suggest that the two lists should be combined into a single list of a compound data type. This isn't practical at all for my application. All I want to do is write a static function that somehow sorts one list based on the elements of another.</p>
 

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