如何按Dictionary <string,int =“”>对列表<string>进行排序

时间:2016-05-09 17:06:51

标签: c# linq

我在.NET 4.0(C#)中实现数据挖掘算法,LINQ将起作用,我需要一些帮助。

我有一个列表A和一个字典B.如何按值B排序A.例如A = {b, d, c}B = {(b,2),(c,5),(d,1),(e,3)}。我需要排序A - &gt; A = {c, b, d}

2 个答案:

答案 0 :(得分:9)

您要求OrderByOrderByDescending个分机:

List<string> A = ...
Dictionary<string, int> B = ...

A = A.OrderByDescending(a => B[a]).ToList()

或使用Sort方法:

A.Sort((x, y) => B[y].CompareTo(B[x]));

答案 1 :(得分:1)

试试这个

           List<string> A = new List<string>() {"b", "d", "c"};
            Dictionary<string,int> B = new Dictionary<string,int>() {{"b",2},{"c",5},{"d",1},{"e",3}};

            List<string> results = A.AsEnumerable().Select(x => new { A = x, i = B[x] }).OrderByDescending(y => y.i).Select(z => z.A).ToList();