TheAuzzieJesus TheAuzzieJesus - 8 months ago 34
C# Question

Sorting a list by the values found in another list C#

Let's say I have the following two lists..

var unscoredList = new List<string> { "John", "Robert", "Rebecca" };

var scoredList = new List<WordScore>
new WordScore("John", 10),
new WordScore("Robert", 40),
new WordScore("Rebecca", 30)

Is there a way I can sort the values in
by the values in
where the word with the highest score appears first in

Below is the WordScore class if required..

public class WordScore {
public string Word;
public int Score;

public WordScore(string word, int score) {
Word = word;
Score = score;

Rob Rob

If you don't need an in-place sort, you can do this:

var scoreLookup = scoredList.ToDictionary(l => l.Word, l => l.Score);

var result = unscoredList.OrderByDescending(l => scoreLookup[l]);

Alternatively, you can use:

unscoredList.Sort((l,r) => scoreLookup[r].CompareTo(scoreLookup[l]));

And of course, there should be some sanity checks done (duplicate values in scoredList, values in unscoredList which are not in scoredList, etc).