c#使用linq排序字典
我在c#中有一本字典:
public Dictionary
我想将结果列入通用列表:
List productList = new List();
产品orderder以字典中的int值降序。 香港专业教育学院尝试使用orderby方法,但没有成功。 谢谢!
你可以这样做:
List productList = dictionary.OrderByDescending(kp => kp.Value) .Select(kp => kp.Key) .ToList();
MyDict.OrderByDescending(x => x.Value).Select(p => p.Key).ToList();
试试这个
List productList = dictionary.OrderByDescending(x => x.Value).Select(x => x.Key).ToList();
这是使用LINQ查询语法的示例。
public class TestDictionary { public void Test() { Dictionary dict=new Dictionary(); dict.Add(new Product(){Data = 1}, 1); dict.Add(new Product() { Data = 2 }, 2); dict.Add(new Product() { Data = 3 }, 3); dict.Add(new Product() { Data = 4 }, 9); dict.Add(new Product() { Data = 5 }, 5); dict.Add(new Product() { Data = 6 }, 6); var query=(from c in dict orderby c.Value descending select c.Key).ToList(); } [DebuggerDisplay("{Data}")] public class Product { public int Data { get; set; } } }