Tung Kieu
Tung Kieu

Reputation: 79

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}.

Upvotes: 2

Views: 128

Answers (2)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

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

Upvotes: 9

jdweng
jdweng

Reputation: 34421

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

Upvotes: 1

Related Questions