Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C# equivalent of PHP's array_key_exists?

Does C# have any equivalent of PHP's array_key_exists function?

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 would I turn this into C#?

like image 718
sczdavos Avatar asked May 19 '12 19:05

sczdavos


Video Answer


1 Answers

Sorry, but dynamic arrays like PHP are not supported in C#. What you can do it create a Dictionary<TKey, TValue>(int, int) and add using .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
}
like image 200
Cole Tobin Avatar answered Sep 17 '22 03:09

Cole Tobin