This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Set array key as string not int?
I know you can do something like
$array["string"] in php but can you also do something like this in C# instead of using arrays with numbers?
Arrays in PHP are in reality more like dictionaries in C#. So yes, you can do this, using a Dictionary<string, YourValueType>:
var dict = new Dictionary<string, int>();
dict["hello"] = 42;
dict["world"] = 12;
If you want to store key/value pairs, you could probably use a Dictionary:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
In PHP the "array" class is actually a map, which is a data structure that maps values to keys.
In C# there are a lot of distinct data structure classes. Each with it's own characteristics.
Wikipedia is a good starting point to read about basic data structures in general:
http://en.wikipedia.org/wiki/Data_structure#Common_data_structures
Use Dictionary for this purpose :)
var dictionary = new Dictionary<string, string>();
dictionary["key"] = "value";
and so on
var ar = new string[]{"one", "two"};
Related
any way to loop in a json file and print all keys and values like a dictionary?
Example
foreach (string item in result.Data.Keys)
{
Debug.LogError("KEY:"+item);
Debug.LogError("Value:" + result.Data[item]);
}
I have tried JsonUtility and simple json, but i cant print the KEY value yet
Any solution? thanks
The built-in JsonUtility class is limited to deserializing into plain classes and structs. Deserialization into dictionaries does not seem to be supported at this time. LitJSON is quite a bit more flexible.
Using LitJSON:
var deserializedObject = JsonMapper.ToObject(json_text);
foreach(var key in deserializedObject.Keys)
{
var value = deserializedObject[key]
}
You could try using FullSerializer instead for your JSON files which is a bit more powerful than the standard JSON Utility. It is available from https://github.com/jacobdufault/fullserializer.
In this case you can use the fsData.AsDictionary to convert it to a regular dictionary.
fsData data = fsJsonParser.Parse(serializedString);
// do something with `data.AsDictionary`
Then you would iterate over the resulting Dictionary as normal.
I had a situation where I was creating a key from concatenating a numerical id number and a string value which created a unique value.
Does it make a difference in the how Dictionary works, or hashtable density or are there any performance implications if the number is first or the string is first the key itself being a string?
for example:
Dictionary<string, bool> dict = new Dictionary<string, bool>();
dict.Add(integerValue + "-" + stringValue, true);
OR
Dictionary<string, bool> dict = new Dictionary<string, bool>();
dict.Add(stringValue + "-" + integerValue, true);
Trying to build strings a certain way for keys in dictionaries to improve performance is 1000% premature optimization, and will not help.
C# Dictionaries use GetHashCode to build the internal structure. The results of GetHashCode are platform specific, encoding specific, and should NEVER be assumed to have a certain distribution to micro-optimize.
https://msdn.microsoft.com/en-us/library/system.string.gethashcode(v=vs.110).aspx
Optimize by measuring. Not by making stabs in the dark about ways to try to mess with the internals of established algorithms. And above all else, optimize when you notice something is slow. Not before.
This can probably be accomplished very easily but I have the following statement in VBA:
Type testType
integerArray(5 To 100) As Double
End Type
How can I accomplish the same in C#?
#Edit 14:16 08-07-2015
In my belief this is not the same as the question mentioned. This is a question how to convert the Type statement with an array inside. The question mentioned is only about an array with it's starting index.
Actually C# does not support those kind of arrays based on any other start-index then zero.
However you may do.
double[] myArray = new double[96];
Alternatvily you may create a dictionary with indexes as keys and the actual value:
var myDict = new Dictionary<int, double>();
I started reading C# in depth. Now I'm in the journey of Generics. I came across the first example of Generics in this book as:
static Dictionary<string,int> CountWords(string text)
{
Dictionary<string,int> frequencies;
frequencies = new Dictionary<string,int>();
... //other code goes here..
And after this code, author says that:
The CountWords method first creates an empty map from string to int
This looks vague to me, as a novice in C#, what the author is trying to mean string to int(in the above statement)? I'm bit confused with this line.
Thanks in advance.
Lets say we want to count the words in a paragraph:
I started reading C# in depth. Now I am in the journey of Generics.
I came across the first example of Generics in this book as
In order to count the words, you'll need some data structure that will be able to store a number of occurrences for each of the words, that will basically attach a number to a string, like
I - 3 times
in - 3 times
Generics - 2 times
etc...
that structure maps a string to an integer, and in C# Generics, that structure is a Dictionary<string,int>
BTW, if you are a C# beginner, i would recommend against C# in depth, which, while being a great book, assumes a quite advanced reader.
He means that string is your key and int is the value paired with the key.
Dictionary<string,int> maps a string key (or lookup) to an int value.
Consider Dictionary<string,int> frequencies.
When you try to add an item you use (for example)
frequencies.Add("key3", 3)
When you add another item you cannot repeat "key3", because in Dictionary that's a unique key; so you create a "map" because you are sure you have unique keys and you can recall values using their key: frequencies["key3"]...
Dictionary<string, int> frequencies = new Dictionary<string, int>();
frequencies.Add("key3", 3);
frequencies.Add("key4", 4);
frequencies.Add("key3", 5); // This raises an error
int value = frequencies["key3"];
This function counts all words in a given string. In the returned dictionary exist for every found word one entry with the word as key. In the int value is stored, how many times this word was found in the string.
It means from the Key to the Value
This might be a very silly / stupid question, but, my defence is that I am a beginner!
Suppose I have a dictionary in c# :
Dictionary<int,string> D = new Dictionary<int,string>();
If I wanted to add all values (which is string) instead of looping and appending all values to a stringBuilder, i do:
string.Join(",",D.values.ToArray());
which works fine. Now, If I want to add all the keys (which is int) to a total, is there a similar way to do this? I dont want to loop through (unless that is the only way) each item and add them. I am not talking about D.Add() which adds a new item, but Math addition, like Key 1 + key 2 etc..
Thanks!
D.Keys.Sum();
will do just what you think it should
By its very definition, adding together numbers requires that you "loop through each one of them".
var total = D.Keys.Sum()
int x = D.Keys.Sum(); or D.Keys.ToList<int>().Sum()
actually you dont need to use to list at all