c# - 根据在另一个列表 C# 中找到的值对列表进行排序

标签 c# linq list sorting

假设我有以下两个列表..

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)
};

有没有一种方法可以根据 scoredList 中的值对 unscoredList 中的值进行排序,其中得分最高的单词首先出现在 unscoredList 中>?

如果需要,下面是 WordScore 类..

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

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

最佳答案

如果你不需要就地排序,你可以这样做:

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

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

或者,您可以使用:

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

当然,应该进行一些合理性检查(scoredList 中的重复值、unscoredList 中不在 scoredList 中的值等)。

关于c# - 根据在另一个列表 C# 中找到的值对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39824327/

相关文章:

c# - 使用 C++ dll 的 C# 应用程序中的堆栈溢出

c# - 将 EnumerableRowCollection<string> 转换为 List<string>

c# - LINQ 按嵌套集合过滤列表

python - 在python中删除列表中的项目

c# - 用户可写配置文件的示例?

c# - 在 c# 中从播放器上的 dvd 加载加密媒体文件,而无需在硬盘上复制

mysql - ASP.NET MVC 应用程序的数据库和逻辑层

python - 类型错误 : object of type 'filter' has no len()

c# - 如何刷新 Windows Phone 中的列表框

c# - 有没有一种使用正则表达式解析大文件的快速方法?