The*_*sus 1 c# linq sorting list
假设我有以下两个列表..
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)
};
Run Code Online (Sandbox Code Playgroud)
有没有办法我可以unscoredList通过scoredList首先出现得分最高的单词的值对值进行排序unscoredList?
如果需要,下面是WordScore类.
public class WordScore {
public string Word;
public int Score;
public WordScore(string word, int score) {
Word = word;
Score = score;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要就地排序,则可以执行以下操作:
var scoreLookup = scoredList.ToDictionary(l => l.Word, l => l.Score);
var result = unscoredList.OrderByDescending(l => scoreLookup[l]);
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用:
unscoredList.Sort((l,r) => scoreLookup[r].CompareTo(scoreLookup[l]));
Run Code Online (Sandbox Code Playgroud)
当然,应该进行一些完整性检查(scoredList中的重复值,unscoredList中不在scoredList中的值等).
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |