What C# construct map to PHP arrays? - c#

I will just list out some arrays and ask how to do them in C#.
$myArray = array();
In PHP I don't have to declare a memory size for the array. What if I don't know big I need my array?
$myArray = array("Name" => "Steve");
How do I do the above in C#?
$myArray = array();
$myArray['Names'][0] = "Steve";
$myArray['Names'][1] = "Jim";
How does the above work in C#"?

$myArray = array("Name" => "Steve");
This is a map. PHP doesn't need you to know that, but C# does. You would implement this as:
var myArray = new Dictionary<String, String>();
For your second case
$myArray['Names'][0] = "Steve";
This is a dictionary where the keys are Strings, but the values are String[]. In C#:
var myArray = new Dictionary<String, List<String>>();

arrays in PHP are most like maps or C# Dictionary . An array in PHP is actually what is called an associative array . So for your code above the C# equivalent is:
Dictionary<string, string> items= new Dictionary<string, string>();
items.Add("Name", "Steve");
if you want a key to point to multiple values:
Dictionary<string, ICollection<string>> items= new
Dictionary<string, ICollection<String>>();
ICollection<string> names = new List<string>();
names.Add("Steve");
items.Add("Name", names);

Related

Get Values from dictionary present in List

I have a list like,
List<string> list = new List<string>();
list.Add("MEASUREMENT");
list.Add("TEST");
I have a dictionary like,
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("BPGA", "TEST");
dict.Add("PPPP", "TEST");
dict.Add("RM_1000", "MEASUREMENT");
dict.Add("RM_2000", "MEASUREMENT");
dict.Add("CDMA", "TEST");
dict.Add("X100", "XXX");
Now, I want to get all matched data from dictionary based on list.
Means, all data from list match with dict value then get new dictionary with following mathched values
Is there any way to achieve this by using lambda expression?
I want result like this.
Key Value
"BPGA", "TEST"
"PPPP", "TEST"
"RM_1000", "MEASUREMENT"
"RM_2000", "MEASUREMENT"
"CDMA", "TEST"
Thanks in advance!
You should be using the dictionary like it is intended to be used i.e. a common key with multiple values for example:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
Then all you need to do when adding the values is:
dict.Add("TEST", new List<string>() { /*strings go in here*/ });
Then to get all the results from a key like:
List<string> testValues = dict["TEST"];
To make it safe however you should check that the key exists i.e.
if (dict.ContainsKey("TEST"))
{
//Get the values
}
Then to add values to a current key you go do something like:
dict["TEST"].Add("NewValue");
If you insist on keeping the same structure, although I do not recommend it, something like the following will work:
List<string> testKeys = new List<string>();
foreach (var pairs in dict)
{
if (pair.Value == "TEST")
{
testKeys.Add(pair.Key);
}
}
Or even the following LINQ statement:
List<string> testKeys = dict.Where(p => p.Value == "TEST").Select(p => p.Key).ToList();
For a generic query to find the ones from your list use:
List<string> values = dict.Where(p => list.Contains(p.Value)).ToList();

accessing a dictionary with an array of key values

I have a dictionary with an array in it defined as:
Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();
is there a way in c# to access specific values in the dictionary without the foreach iteration.
Try this:
var t = wordDictionary ["myKey"][myArrIndex]
For example, this will give you the whole array:
var t = wordDictionary ["myKey"]
while this will give you the value in the array at position 5:
var t = wordDictionary ["myKey"][5]
If you know the key you can access it like this:
string[] str=wordDictionary["yourString"];
What about this?
string firstFoo = wordDictionary["foo"][0]

C# PHP style array keys

I have a string array:
String[] array1 = new String[10];
Is there anyway I can use keys which are nto numbers?
array["keyhere"] instead of array1[1]
anyone know how?
Use System.Collections.Generic.Dictionary<TKey, TValue>.
For example:
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
myDictionary.Add("key", "value");
string foo = myDictionary["key"];
Dictionary<TKey, TValue> has some methods that you might find useful, such as ContainsKey().
Use a dictionary
Dictionary<String,Object> phpArray = new Dictionary<String,Object>();
phpArray.Add("keyhere",1);
MessageBox.Show(phpArray["keyhere"]);
PHP arrays are called associative arrays. You can use either a Dictionary or HashMap to implement the same thing in C#.

Help me convert this 2d array code from PHP to C#

Please help me re-write this code sample in PHP to C#:
$stringArray = array();
$stringArray['field1'] = 'value1';
$stringArray['field2'] = 'value2';
$stringArray['field3'] = 'value3';
foreach ($stringArray as $key => $value)
{
echo $key . ': ' . $value;
echo "\r\n";
}
Named arrays do not exist in C#. An alternative is to use a Dictionary<string, string> to recreate a similar structure.
Dictionary<string, string> stringArray = new Dictionary<string, string>();
stringArray.Add("field1", "value1");
stringArray.Add("field2", "value2");
stringArray.Add("field3", "value3");
In order to iterate through them, you can use the following:
foreach( KeyValuePair<string, string> kvp in stringArray ) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
var map = new Dictionary<String, String>
{
{ "field1", "value1" },
{ "field2", "value2" },
{ "field3", "value3" }
}
Or without the collection initializer.
var map = new Dictionary<String, String>();
map["field1"] = "value1";
map["field2"] = "value2";
map["field3"] = "value3";
There is even a specialized class StringDictionary to map string to strings in the often overlooked namespace System.Collections.Specialized, but I prefer Dictionary<TKey, TValue> because it implements a richer set of interfaces.
You are trying to recreate an associative array - in C# I would usually use a Dictionary
Dictionary<string,string> stringArray = new Dictionary<string,string>();
and then you can assign values in two ways
stringArray["field1"] = "value1";
stringArray.Add("field2","value2");
Dictionaries can be used to store any key/value pair combination, such as:
Dictionary<int,string>()
Dictionary<long,KeyValuePair<string,long>>()
etc.
If you absolutely know that you only need a key that is a string that will be returning a value that is a string then you can also use a NameValueCollection
NameValueCollection stringArray = new NameValueCollection();
and again you can use the same two methods to add values
stringArray["field1"] = "value1";
stringArray.Add("field2","value2");
Both datatypes also have other convenience methods like
stringArray.Clear(); // make it empty
stringArray.Remove("field1"); // remove field1 but leave everything else
check out your intellisense in visual studio for more good stuff
Additional nodes
Note that a NameValueColelction does not (solely) provide a one-to-one mapping - you can associate multiple values with a single name.
var map = new NameValueCollection();
map.Add("Bar", "Foo");
map.Add("Bar", "Buz");
// Prints 'Foo,Buz' - the comma-separated list of all values
// associated with the name 'Bar'.
Console.WriteLine(map["Bar"]);

How to use nested dictionary in C#?

My requirement is
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>
When I try to get the value of the inner Dictionary using key(outerString), it gives an error saying "cannot apply indexing with type of expression...............".
I have tried this
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>;
Dictionary<innerString, List<SelectListItem>> dict2 = dict1.values["outerString"];
Any quick help will be greatly appreciated.
Thx in advance.
I guess what you need is just:
Dictionary<innerString, List<SelectListItem>> dict = dict1["someKey"];
You just need to change the last line of your code snippet to (I assumed where you wrote inner string and outer string you must meant string):
var dict = dict1["someValue"];
Additionally, you could probably make your code much readable with the var keyword:
var dict1 = new Dictionary<string, Dictionary<string, List<SelectListItem>>>();
var dict = dict1["someValue"];
So outerString and innerString are types? Did you actually just want a nested dictionary string -> string -> List<SelectListItem> ? If not, you'll have to show us the definition of these types, and give the compiler some way to convert from the string you are trying to index with...
You were close:
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>();
// Get inner dictionary whose key is "someValue"
Dictionary<innerString, List<SelectListItem>> dict = dict1["someValue"]
Did I misunderstand you? This works fine
Dictionary<string, Dictionary<string, List<string>>> list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];
or
var list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];
In
Dictionary<string, Dictionary<string, List<T>> dict1 =
new Dictionary<string, Dictionary<string, List<T>>();
you need
List<T> list12 = dict1["key1"]["key2"];
List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
Dictionary<string, List<int>> innerDict = new Dictionary<string, List<int>>();
innerDict.Add("inner", list1);
Dictionary<string, Dictionary<string, List<int>>> dict1 =
new Dictionary<string, Dictionary<string, List<int>>>();
dict1.Add("outer", innerDict);
List<int> list2 = dict1["outer"]["inner"];
How about you use an array of strings for a key, rather than trying to nest the dictionaries -
Dictionary<string[], List<string>> dict =
new Dictionary<string[],List<string>>();
string[] key = {"inner", "outer"};
List<string> vals = new List<string>();
dict.Add(key, vals);

Categories

Resources