C # Sort key-value pairs

Source: Internet
Author: User

Summarize the sorting methods of key-value pairs. [Csharp]/* use the sort dictionary. By default, only SortedDictionary <DateTime, String> dd = new SortedDictionary <DateTime, String> (); DateTime dt = DateTime. now; dd. add (dt, "bbb"); dd. add (dt. addDays (-1), "ccc"); dd. add (dt. addDays (1), "aaa"); // you can use List to obtain the descending key or value List <String> lst = new List <String> (dd. values); lst. reverse (); * // * use Linq to query Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> (); DateTime dt = DateTime. now; dd. add (dt, "bbb"); dd. add (dt. addDays (-1), "ccc"); dd. add (dt. addDays (1), "aaa"); var result = from pair in dd orderby pair. key descending select pair; List <String> lst = new List <String> (); foreach (var kv in result) {www.2cto.com lst. add (kv. value);} // or Dictionary <DateTime, String> dd2 = result. toDictionary (p => p. key, p => p. value); * // use the extended method Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> (); DateTime dt = DateTime. now; dd. add (dt, "bbb"); dd. add (dt. addDays (-1), "ccc"); dd. add (dt. addDays (1), "aaa"); Dictionary <DateTime, String> dicAsc = dd. orderBy (p => p. key ). toDictionary (p => p. key, p => p. value); 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.