Computer >> Máy Tính >  >> Lập trình >> C#

Lấy các khóa trong đối tượng SortedList C #

Để lấy các khóa trong đối tượng SortedList, mã như sau -

Ví dụ

 using System; using System.Collections; public class Demo {public static void Main (String [] args) {SortedList list =new SortedList (); list.Add ("Một", "Tài chính"); list.Add ("Hai", "Tiếp thị"); list.Add ("Ba", "Doanh thu"); list.Add ("Bốn", "Mua"); list.Add ("Năm", "Hoạt động"); list.Add ("Sáu", "IT"); Console.WriteLine ("Các phần tử trong danh sách đã được sắp xếp ..."); foreach (DictionaryEntry d trong danh sách) {Console.WriteLine (d.Key + "" + d.Value); } Console.WriteLine ("\ nIndex at key One =" + list.IndexOfKey ("One")); ICollection col =list.Keys; Console.WriteLine ("\ nTập hợp các phím ..."); foreach (string res in col) Console.WriteLine (res); }} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

 Các yếu tố của danh sách đã sắp xếp ... Năm hoạt độngMua hàng thứ tưMột khoản tài chínhSix ITThree Bán hàngHai MarketingIndex tại key Một =2Tổng hợp các phím ... FiveFourOneSixThreeTwo 

Ví dụ

Hãy để chúng tôi xem một ví dụ khác -

 using System; using System.Collections; public class Demo {public static void Main (String [] args) {SortedList list1 =new SortedList (); list1.Add ("Một", 1); list1.Add ("Hai", 2); list1.Add ("Ba", 3); list1.Add ("Bốn", 4); list1.Add ("Năm", 5); list1.Add ("Sáu", 6); list1.Add ("Bảy", 7); list1.Add ("Tám", 8); list1.Add ("Chín", 9); list1.Add ("Ten", 10); Console.WriteLine ("Các phần tử SortedList1 ..."); foreach (DictionaryEntry d trong list1) {Console.WriteLine (d.Key + "" + d.Value); } ICollection col =list1.Keys; Console.WriteLine ("\ nTập hợp các khóa trong List1 ..."); foreach (string res in col) Console.WriteLine (res); SortedList list2 =new SortedList (); list2.Add ("A", "Phụ kiện"); list2.Add ("B", "Sách"); list2.Add ("C", "Công nghệ có thể đeo thông minh"); list2.Add ("D", "Thiết bị gia dụng"); Console.WriteLine ("\ nSortedList2 phần tử ..."); foreach (DictionaryEntry d trong list2) {Console.WriteLine (d.Key + "" + d.Value); } col =list2.Keys; Console.WriteLine ("\ nTập hợp các khóa trong List2 ..."); foreach (string res in col) Console.WriteLine (res); }} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Phần tử
 SortedList1 ... Tám phần tử 8Five 5Four 4Nine 9One 1Seven 7Six 6Ten 10Three 3Thai 2Thu tập các phím trong danh sách1 ... EightFiveFourNineOneSevenSixTenThreeTwoSortedList2 phần tử ...>