Is there a C # equivalent for PHP array_key_exists?

Does C # have any equivalent PHP function array_key_exists ?

For example, I have this PHP code:

$array = array(); $array[5] = 4; $array[7] = 8; if (array_key_exists($array, 2)) echo $array[2]; 

How can I turn this into C #?

+6
source share
4 answers

Sorry, but dynamic arrays like PHP are not supported in C #. What you can do is create a Dictionary <TKey, TValue> (int, int) and add with . Add (int, int)

 using System.Collections.Generic; ... Dictionary<int, int> dict = new Dictionary<int, int>(); dict.Add(5, 4); dict.Add(7, 8); if (dict.ContainsKey(5)) { // [5, int] exists int outval = dict[5]; // outval now contains 4 } 
+6
source

In C #, when you declare a new array, you must provide it with a size for memory allocation. If you create an int array, the values ​​are pre-populated when the instance is created, so keys will always exist.

 int[] array = new int[10]; Console.WriteLine(array[0]); //outputs 0. 

If you need an array with dynamic size, you can use List .

 List<int> array = new List<int> array.push(0); if (array.Length > 5) Console.WriteLine(array[5]); 
+5
source

An array in C # has a fixed size, so you must declare an array of 8 integers

 int[] array = new int[8]; 

You only need to check the length

 if(array.Length > 2) { Debug.WriteLine( array[2] ); } 

This is great for value types, but if you have an array of reference types like

 Person[] array = new Person[8]; 

then you will need to check for null, as in

 if(array.Length > 2 && array[2] != null) { Debug.WriteLine( array[2].ToString() ); } 
+4
source

You can use ContainsKey

 var dictionary = new Dictionary<string, int>() { {"mac", 1000}, {"windows", 500} }; // Use ContainsKey method. if (dictionary.ContainsKey("mac") == true) { Console.WriteLine(dictionary["mac"]); // <-- Is executed } // Use ContainsKey method on another string. if (dictionary.ContainsKey("acorn")) { Console.WriteLine(false); // <-- Not hit } 
+1
source

Source: https://habr.com/ru/post/916169/


All Articles