C # generic learning notes

Source: Internet
Author: User

In this blog, I will mainly talk about the usage of generic types in C #, that is, the use of List and Dictionary sets. Here I will mainly talk about how to use them, instead of studying the bottom layer of generics in a long article, we are studying some programs so that learning can quickly learn a set and then study some advanced usage of the set by ourselves, some common small cases are not listed at the end.

  1. Generic set

(1) a generic set is an uncertain set. In the syntax, there is an angle bracket. What type is put in it, and what type is this set?

(2) List

1) Example:

static void Main(string[] args){        List<int> listInt = new List<int>();        listInt.AddRange(new int[] { 1, 34, 54, 65, 76, 78 });        int sum = 0;        for (int i = 0; i < listInt.Count; i++)          {                 sum += listInt[i];         }         Console.WriteLine(sum);         Console.ReadKey();}

(3) Dictionary (Dictionary <TKey, TValue>)

Define a generic set: Dictionary <TKey, Tvalue> dic = new Dictionary <TKey, Tvalue> ();

1) Add

Add adds the specified key-value pair to the dictionary set.

Method prototype: void dic. Add (T key, T Value)

Dictionary <string, string> openWith = new Dictionary <string, string> (); try {openWith. add ("txt", "notepad.exe"); openWith. add ("bmp", "paint.exe"); openWith. add ("dib", "paint.exe"); openWith. add ("rtf", "wordpad.exe"); openWith. add ("txt", "winword.exe");} catch (ArgumentException) {Console. writeLine ("failed to add, please check ");}

// The output result is an error occurred while adding the key. Check that the same key is added.

2) Delete

Remove the specified key value from the dictionary set

Method prototype: bool dic. Remove (TKey key );

Dictionary <string, string> openWith = new Dictionary <string, string> (); openWith. add ("txt", "notepad.exe"); openWith. add ("bmp", "paint.exe"); openWith. add ("dib", "paint.exe"); openWith. add ("rtf", "wordpad.exe"); openWith. remove ("txt"); foreach (var item in openWith) {Console. writeLine (item. key);} // output result: bmp dib rtfClear removes all value methods from the dictionary set. prototype: void dic. clear (); Dictionary <string, string> openWith = new Dictionary <string, string> (); openWith. add ("txt", "notepad.exe"); openWith. add ("bmp", "paint.exe"); openWith. add ("dib", "paint.exe"); openWith. add ("rtf", "wordpad.exe"); openWith. clear (); foreach (var item in openWith) {Console. writeLine (item. key);} // The output result is null.

3) Query

ContainsKey is used to obtain whether the dictionary set contains the specified key.

Method prototype: bool dic. ContainsKey (TKey, key );

Dictionary <string, string> openWith = new Dictionary <string, string> (); openWith. add ("txt", "notepad.exe"); openWith. add ("bmp", "paint.exe"); openWith. add ("dib", "paint.exe"); openWith. add ("rtf", "wordpad.exe"); if (! OpenWith. ContainsKey ("txt") {openWith. Add ("txt", "notepat ++");} else {Console. WriteLine ("already exists ");}

// Output result: already exists

COntainsValue: determines whether the dictionary set contains the specified value.

Method prototype: bool dic. ContainsValue (TValue, value );

Dictionary <string, string> openWith = new Dictionary <string, string> ();

OpenWith. Add ("txt", "notepad.exe ");

OpenWith. Add ("bmp", "paint.exe ");

OpenWith. Add ("dib", "paint.exe ");

OpenWith. Add ("rtf", "wordpad.exe ");

If (openWith. ContainsValue ("paint.exe "))

{

Console. WriteLine ("already exists ");

}

// Output result: already exists

4) TryGetValue is obtained from the value associated with the specified key.

Method prototype: bool dic. TryGetValue (TKey key, out TVlaue value );

Dictionary <string, string> openWith = new Dictionary <string, string> (); openWith. add ("txt", "notepad.exe"); openWith. add ("bmp", "paint.exe"); openWith. add ("dib", "paint.exe"); openWith. add ("rtf", "wordpad.exe"); string value = ""; if (openWith. tryGetValue ("rtf", out value) {Console. writeLine ("Key = rtf, value = {0}", value) ;}else {Console. writeLine ("the corresponding value is not found based on the rtf key ");}

// Output result: key‑rtf,value‑wordpad.exe

1) Example:

Static void Main (string [] args)

{

Dictionary <char, string> dic = new Dictionary <char, string> ();

Dic. Add ('1', "love ");

Foreach (KeyValuePair <char, string> item in dic)

{

Console. WriteLine (item );

}

Console. ReadKey ();

}

(4) Case 1: use generic programs for sorting odd numbers

Static void Main (string [] args) {string str = "3 45 65 34 68 67 87 98"; // 1 split string [] nums = str. split (new char [] {''}, StringSplitOptions. removeEmptyEntries); // 2 list <string> List <string> odd = new List <string> (); // odd List <string> even = new List <string> (); // even number // 3 for loop judge parity for (int I = 0; I <nums. length; I ++) {// method 1 // int num = Convert. toInt32 (nums [I]); // if (num % 2 = 0) // {// even. add (nums [I]); // else // {// odd. add (nums [I]); // method 2 string num = nums [I]; char ch = num [num. length-1]; int last = ch-'0'; if (nums [I] [nums [I]. length-1]-'0') % 2 = 0) {even. add (nums [I]);} else {odd. add (nums [I]) ;}} odd. addRange (even); // 4 switch Console. writeLine (string. join ("", odd. toArray ()));}

(5) Case 2: place the odd number in the int array into a new int array and return

 static void Main(string[] args)        {            int[] nums = { 1, 3, 5, 565, 76, 78, 98, 90, 4, 545 };            List<int> listInt = new List<int>();            for (int i = 0; i < nums.Length; i++)            {                if (nums[i] % 2 == 1)                {                    listInt.Add(nums[i]);                }            }            for (int i = 0; i < listInt.Count; i++)            {                Console.WriteLine(listInt[i] + " ");            }            Console.ReadKey();        }

(6) Case 3: retrieve the maximum number from an integer List <int>

static void Main(string[] args)        {            int[] nums = { 2, 34, 454, 65, 76, 77, 778, 898, 989 };            int max = int.MinValue;            int min = int.MaxValue;            List<int> listInt = new List<int>();            listInt.AddRange(nums);            for (int i = 0; i < listInt.Count; i++)            {                if (min > listInt[i])                {                    min = listInt[i];                }                if (max < listInt[i])                {                    max = listInt[i];                }            }            Console.WriteLine(max);            Console.WriteLine(min);        }

(7) convert 123 to ""

Static void Main (string [] args) {string var = ""; Dictionary <char, char> dic = new Dictionary <char, char> (); for (int I = 0; I <var. length; I ++) {dic. add (char) (I + '0'), var [I]);} while (true) {Console. write ("enter a line of numbers:"); string str = Console. readLine (); StringBuilder sb = new StringBuilder (); for (int I = 0; I <str. length; I ++) {char num = str [I]; char word = dic [num]; sb. append (word);} Console. writeLine (sb. toString (); Console. readKey ();}}

(8) calculate the number of occurrences of each character in a string

Static void Main (string [] args) {Dictionary <char, int> dic = new Dictionary <char, int> (); Console. write ("enter a sentence"); string str = Console. readLine (); for (int I = 0; I <str. length; I ++) {// dic. add (str [I], 1); // dic [str [I] ++; char current = str [I]; if (dic. containsKey (current) {// If the set does not contain this data // dic [current] + = 1; dic [current] ++ ;} else {// This data dic does not exist in the collection. add (current, 1) ;}}foreach (KeyValuePair <char, int> item in dic) {Console. writeLine ("the sub-character {0} appears {1} Times", item. key, item. value);} Console. readKey ();}
  1. Dictionary is the generic form of Hashtable

(1) The Hal algorithm is a function.

Add (Key, Value );

Dic [Key];

(2) The hash algorithm is a function that uses keys to calculate addresses.

1) input a key and a value

2) Calculate the key to an address using the hash algorithm

3) store the address to the key-value pair set and store the value to the location where the address is located.

4) when the access is completed, the address is calculated using the key and the stored variable is directly found.

  1. Can I use a for loop to traverse a set of Dic?

(1) If the corresponding incremental sequence number is not used in the for loop, "I" does not think that the for loop is used.

(2) foreach loop Process

1) locate the data source and call the GetEnumertor method to obtain the enumerated value.

2) in, call the MoveNext Method

3) If MoveNext returns true, use Current to get the Current data.

4) if false is returned, the loop jumps out.

Static void Main (string [] args)

{

Dictionary <string, string> dic = new Dictionary <string, string> ();

Dic. Add ("1111", "2222 ");

Dic. Add ("0000", "3333 ");

Var enumrator = dic. GetEnumerator ();

// While (enumrator. MoveNext ())

//{

// Console. WriteLine (enumrator. Current. Key + "," + enumrator. Current. Value );

//}

For (; enumrator. MoveNext ();)

{

Console. WriteLine (enumrator. Current. Key + "," + enumrator. Current. Value );

}

}

  1. Equal

(1) Equals determines whether the specified Object is of the current Object type

Method prototype:

Bool Equals (Object obj)

Object Obj1 = new Object ();

Object Obj2 = new Object ();

Console. WriteLine (Obj1.Equals (Obj2 ));

Obj2 = Obj1;

Console. WriteLine (Obj1.Equals (Obj2 ));

Output result: False, True

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.