C # Sort data by key-value pairs,

Source: Internet
Author: User

C # Sort data by key-value pairs,

Summarize the sorting methods of key-value pairs.

 

[Csharp]View plaincopy
  1. /* Use the sort dictionary. By default, only the ascending order is supported.
  2. SortedDictionary <DateTime, String> dd = new SortedDictionary <DateTime, String> ();
  3. DateTime dt = DateTime. Now;
  4. Dd. Add (dt, "bbb ");
  5. Dd. Add (dt. AddDays (-1), "ccc ");
  6. Dd. Add (dt. AddDays (1), "aaa ");
  7. // You can use List to obtain the descending key or value.
  8. List <String> lst = new List <String> (dd. Values );
  9. Lst. Reverse ();
  10. */
  11. /* Query using Linq
  12. Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> ();
  13. DateTime dt = DateTime. Now;
  14. Dd. Add (dt, "bbb ");
  15. Dd. Add (dt. AddDays (-1), "ccc ");
  16. Dd. Add (dt. AddDays (1), "aaa ");
  17.  
  18. Var result = from pair in dd orderby pair. Key descending select pair;
  19. List <String> lst = new List <String> ();
  20. Foreach (var kv in result)
  21. {
  22. Lst. Add (kv. Value );
  23. }
  24. // Or
  25. Dictionary <DateTime, String> dd2 = result. ToDictionary (p => p. Key, p => p. Value );
  26. */
  27. // Use the Extension Method
  28. Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> ();
  29. DateTime dt = DateTime. Now;
  30. Dd. Add (dt, "bbb ");
  31. Dd. Add (dt. AddDays (-1), "ccc ");
  32. Dd. Add (dt. AddDays (1), "aaa ");
  33. Dictionary <DateTime, String> dicAsc = dd. OrderBy (p => p. Key). ToDictionary (p => p. Key, p => p. Value );
  34. Dictionary <DateTime, String> dicDesc = dd. OrderByDescending (p => p. Key). ToDictionary (p => p. Key, p => p. Value );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.