C# 사전
Sep 03, 2024 pm 03:31 PMC#의 Dictionary 클래스는 Dictionary<TKey, Tvalue>로 표현됩니다. 이는 두 개 이상의 언어로 된 단어 컬렉션과 해당 정의로 구성된 영어 사전과 유사한 컬렉션이지만 C#의 사전은 키가 단어를 나타내고 값이 정의를 나타내는 키와 값 컬렉션으로 구성됩니다. 이 사전<TKey, Tvalue> C#의 클래스는 System.Collection.Generics 네임스페이스에 속하며 Tkey가 키 유형을 나타내고 Tvalue가 Tvalue 유형과 IDictionary<Tkey, Tvalue>의 변수를 나타내는 일반 컬렉션 클래스입니다. 클래스 또는 Dictionary<Tkey, Tvalue> 클래스는 사전의 모든 개체에 할당될 수 있습니다.
C#의 Dictionary 클래스 구문은 다음과 같습니다.
IDictionary<TKey, TValue> variable_name = new Dictionary<TKey, TValue>();
또는
Dictionary<TKey, TValue > variable_name = new Dictionary<TKey, TValue >();
C#에서 Dictionary 클래스 작업
- System.Collections.Generic 네임스페이스의 중요한 클래스 중 하나는 Dictionary
입니다. 수업. - 일반 데이터 구조는 데이터 키와 해당 값을 포함하는 C#의 사전 클래스로 표현됩니다. 따라서 사전 인스턴스를 사용하여 모든 유형의 데이터를 저장할 수 있습니다.
- ICollection 인터페이스의 확장은 IDictionary 인터페이스입니다.
- 사전 클래스의 Add 메소드는 사전 인스턴스에 객체를 저장하는 데 사용됩니다.
- 사전을 사용하면 박싱 및 언박싱에 따른 오버헤드가 사라집니다.
키만 가져오기 위해 Dictionary 클래스를 사용하는 방법을 설명하려면 아래 예를 고려하세요.
using System; using System.Collections.Generic; //a class called program is defined class program { // main method is called public static void Main() { // a new dictionary is created with key type string and value type string Dictionary<string, string> Dict = new Dictionary<string, string>(); // using add method in dictionary to add the objects to the dictionary Dict.Add("A", "Karnataka"); Dict.Add("B", "Maharashtra"); Dict.Add("C", "Andra"); Dict.Add("D", "TamilNadu"); Dict.Add("E", "Delhi"); Dict.Add("F", "Goa"); // Finding the number of key value pairs in the dictionary Console.WriteLine("The number of key value pairs in the dictionary are : " + Dict.Count); // using the property of keys to get the keys alone from the dictionary Dictionary<string, string>.KeyCollection key = Dict.Keys; // a foreach loop is used to loop around every key in the dictionary and to obtain each key value foreach(string sh in key) { Console.WriteLine("The key is referred as = {0}", sh); } } }
위 프로그램의 출력은 아래 스냅샷과 같습니다.
위 프로그램에서는 프로그램이 정의된 클래스입니다. 그런 다음 기본 메서드가 호출됩니다. 키 유형 문자열과 값 유형 문자열을 사용하여 새 사전이 생성됩니다. 그런 다음 사전의 add 메소드를 사용하여 사전에 객체를 추가합니다. 그런 다음 개수를 사용하여 사전에 있는 키-값 쌍의 개수를 찾습니다. 그런 다음 키 속성을 사용하여 사전에서 키만 추출합니다. 그런 다음 foreach 루프를 사용하여 사전의 모든 키를 반복하고 각 키 값을 얻습니다. 프로그램의 출력은 위의 스냅샷과 같습니다.
C# 사전의 방법
C#의 Dictionary 클래스에는 여러 가지 메서드가 있습니다. 그들은:
1. 추가()
- add() 메소드는 사전 컬렉션에 항목을 추가하는 데 사용됩니다.
- add() 메소드는 Dictionary
컬렉션에 키-값 쌍을 추가하는 데 사용됩니다. - 사전 클래스의 추가 메소드를 보여주기 위해 아래 예를 고려하십시오.
using System; using System.Collections.Generic; //a class called check is defined public class Check { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str.Add(3,"Green"); str.Add(1,"Saffron"); str.Add(2,"White"); str.Add(new KeyValuePair<int, string>(4, "Blue")); //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str.Count); } }
위 프로그램의 출력은 아래 스냅샷과 같습니다.
2. 제거()
Remove() 메소드는 사전에서 지정된 항목의 첫 번째 항목을 제거하는 데 사용됩니다.
remove() 메소드는 사전 객체에서 키와 함께 지정된 요소를 제거하는 데 사용됩니다.
사전 클래스에서 Remove() 메소드의 사용법을 보여주기 위해 아래 예를 고려하십시오.
using System; using System.Collections.Generic; //a class called check1 is defined public class Check1 { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str1 = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str1.Add(3,"Green"); str1.Add(1,"Saffron"); str1.Add(2,"White"); str1.Add(new KeyValuePair<int, string>(4, "Blue")); str1.Remove(1); str1.Remove(new KeyValuePair<int, string>(2, "White")); //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str1.Count); } }
위 프로그램의 출력은 아래 스냅샷과 같습니다.
3. 포함키()
ContainsKey() 메서드는 주어진 키가 Dictionary
사전 클래스에서 ContainsKey() 메서드의 사용법을 보여주기 위해 아래 프로그램을 고려하세요.
using System; using System.Collections.Generic; //a class called2 check is defined public class Check2 { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str2 = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str2.Add(3,"Green"); str2.Add(1,"Saffron"); str2.Add(2,"White"); str2.Add(new KeyValuePair<int, string>(4, "Blue")); str2.Remove(1); str2.Remove(new KeyValuePair<int, string>(2, "White")); Console.WriteLine("If the key 3 is present?{0}", str2.ContainsKey(3)); Console.WriteLine("If the key 2 is present? {0}", str2.Contains(new KeyValuePair<int, string>(2, "White"))); //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str2.Count); } }
위 프로그램의 출력은 아래 스냅샷과 같습니다.
4. 포함값()
ContainsValue() 메소드는 주어진 값이 Dictionary
사전 클래스에서 ContainsValue() 메서드의 사용법을 보여주기 위해 아래 프로그램을 고려하세요.
using System; using System.Collections.Generic; //a class called check3 is defined public class Check3 { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str2 = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str2.Add(3,"Green"); str2.Add(1,"Saffron"); str2.Add(2,"White"); str2.Add(new KeyValuePair<int, string>(4, "Blue")); str2.Remove(1); str2.Remove(new KeyValuePair<int, string>(2, "White")); Console.WriteLine("If the key 3 is present?{0}", str2.ContainsKey(3)); Console.WriteLine("If the key 2 is present? {0}", str2.Contains(new KeyValuePair<int, string>(2, "White"))); //new dictionary of both string key and string value types is defined Dictionary<string, string> stri = new Dictionary<string, string>(); stri.Add("Flag","Green"); Console.WriteLine("If the value Green is present?{0}", stri.ContainsValue("Green")); //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str2.Count); } }
위 프로그램의 출력은 아래 스냅샷과 같습니다.
5. 지우기()
clear() 메소드는 사전 클래스의 모든 객체를 지우는 데 사용됩니다.
사전 클래스에서 ContainsValue() 메서드의 사용법을 보여주기 위해 아래 프로그램을 고려하세요.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; //a class called check4 is defined public class Check4 { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str3 = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str3.Add(3,"Green"); str3.Add(1,"Saffron"); str3.Add(2,"White"); str3.Add(new KeyValuePair<int, string>(4, "Blue")); str3.Remove(1); str3.Remove(new KeyValuePair<int, string>(2, "White")); Console.WriteLine("If the key 3 is present?{0}", str3.ContainsKey(3)); Console.WriteLine("If the key 2 is present? {0}", str3.Contains(new KeyValuePair<int, string>(2, "White"))); //new dictionary of both string key and string value types is defined Dictionary<string, string> stri1 = new Dictionary<string, string>(); stri1.Add("Flag","Green"); Console.WriteLine("If the value Green is present?{0}", stri1.ContainsValue("Green")); //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str3.Count); Console.Clear(); } }
아래 스냅샷과 같이 위 프로그램 공백의 출력은 다음과 같습니다.
6. TryGetValue()
TryGetValue() 메서드는 주어진 키가 존재하는지 확인하고, 존재하지 않으면 false를 반환합니다. 주어진 키가 존재하면 true를 반환하고 지정된 키에 주어진 값을 할당합니다.
Consider the below program to demonstrate the usage of TryGetValue() method of Dictionary class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; //a class called check4 is defined public class Check4 { //main method is called public static void Main() { //a new dictionary is created with key type int and value type string IDictionary<int, string> str3 = new Dictionary<int, string>(); //Add method is used to add objects to the dictionary str3.Add(3,"Green"); str3.Add(1,"Saffron"); str3.Add(2,"White"); str3.Add(new KeyValuePair<int, string>(4, "Blue")); str3.Remove(1); str3.Remove(new KeyValuePair<int, string>(2, "White")); Console.WriteLine("If the key 3 is present?{0}", str3.ContainsKey(3)); Console.WriteLine("If the key 2 is present? {0}", str3.Contains(new KeyValuePair<int, string>(2, "White"))); //new dictionary of both string key and string value types is defined Dictionary<string, string> stri1 = new Dictionary<string, string>(); stri1.Add("Flag","Green"); Console.WriteLine("If the value Green is present?{0}", stri1.ContainsValue("Green")); string res; if(str3.TryGetValue(4, out res)) { Console.WriteLine("The value of the specified key is {0}", res); } else { Console.WriteLine("The specified key is not present."); } //The number of objects in the dictionary is displayed using count Console.WriteLine("The number of objects in the given dictionary is: {0} ", str3.Count); } }
The output of the above program is as shown in the snapshot below:
Conclusion
In this tutorial, we understand the concept of Dictionary class in C# through definition, the syntax of Dictionary class in C#, working of Dictionary class, and their methods through programming examples and their outputs.
위 내용은 C# 사전의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









