C#實戰小技巧(十六):List和Dictionary排序

1.List或List等簡單List排序
調用Sort函數後,list排序變化。
(1)正序

list.Sort((a, b) => a.CompareTo(b));

(2)倒序

list.Sort((b, a) => a.CompareTo(b));

2.List排序
調用Sort函數後,list排序變化,Object是自定義類,startTime是類Object中的一個屬性。
(1)正序

list.Sort((a, b) => a.startTime.CompareTo(b.startTime));

(2)倒序

list.Sort((b, a) => a.startTime.CompareTo(b.startTime));

3.Dictionary<int, int>或Dictionary<int, string>等排序
(1)根據Value正序排序

Dictionary<int, int> sortedResult = result.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value);

(2)根據Value倒序排序

Dictionary<int, int> sortedResult = result.OrderByDescending(o => o.Value).ToDictionary(o => o.Key, o => o.Value);

(3)根據Key正序排序

Dictionary<int, int> sortedResult = result.OrderBy(o => o.Key).ToDictionary(o => o.Key, o => o.Value);

(4)根據Key倒序排序

Dictionary<int, int> sortedResult = result.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, o => o.Value);

4.Dictionary<int, Object>或Dictionary<string, Object>等排序
Object是自定義類,startTime是類Object中的一個屬性。
(1)根據Value的屬性正序排序

Dictionary<string, CallRecordObj> sortedResult = result.OrderBy(o => o.Value.startTime).ToDictionary(o => o.Key, o => o.Value);

(2)根據Value的屬性倒序排序

Dictionary<string, CallRecordObj> sortedResult = result.OrderByDescending(o => o.Value.startTime).ToDictionary(o => o.Key, o => o.Value);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章