简体   繁体   中英

How to sort a list<string> by Dictionary<string, int>

I am implementing Data Mining Algorithm in .NET 4.0 (C#) and LINQ will work and I need some helps.

I have a List A and a Dictionary B. How to sort A by value B. For example A = {b, d, c} and B = {(b,2),(c,5),(d,1),(e,3)} . I need sort A -> A = {c, b, d} .

You are asking for OrderBy or OrderByDescending extensions:

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

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

Or using Sort method:

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM