最新有個需求,要針對List<Dictionary<string, string>>中的某個key的值做排序
List資料如下
List<Dictionary<string, string>> items = new List<Dictionary<string, string>>(); items.Add(new Dictionary<string, string> { { "rank", "1" }, { "username", "UserA" } }); items.Add(new Dictionary<string, string> { { "rank", "5" }, { "username", "UserB" } }); items.Add(new Dictionary<string, string> { { "rank", "2" }, { "username", "UserC" } }); items.Add(new Dictionary<string, string> { { "rank", "4" }, { "username", "UserD" } });
如果要對rank這個key的值做排序怎麼辦?
Google之後找到了簡潔的寫法
由小到大排序
items.Sort( (first, second) => { return first["rank"].CompareTo(second["rank"]); } );
由大到小
items.Sort( (first, second) => { return second["rank"].CompareTo(first["rank"]); } );