How to declare array of strings with string index? - c#

In my code i declared like this :
public string[] s ;
and i need to use this string like this :
s["Matthew"]="Has a dog";
s["John"]="Has a car";
when i use s["Matthew"] an error appears and it says "Cannot implicitly convert 'string' to 'int'" .
How can I make a string array to have string index ?
if i write this in php it works :
array() a;
a["Mathew"]="Is a boy";
I need it to work also in asp.net !

public Dictionary<string, string> s;
MSDN documentation

In C#, you cannot access an array element using, as array index, a string.
For this reason you have that cast error, because the index of an array is, by definition of an array, an integer.
Why don't you use a data structure like a dictionary?
var dict = new Dictionary<string,string>();
dict.Add("John","I am John");
//print the value stored in dictionary using the string key
Console.WriteLine(dict["John"]);

Array works on indexes and indexes are in numbers but you are passing string that's why you are getting error, #Christian suggest you to use Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}

Related

get string array out of Dictionary<int, string[]>

this is my code
pritvate static Dictionary<int, string[]> _list = new Dictionary<int, string[]>();
how can i get the string[] out of this?
I have tried this and a lot more:
string[] s = _list.Values;
but it is all not working.
please help
If you want all string arrays for all keys merged into a single array, you can use LINQ's .SelectMany(...):
var strings = _list.Values.SelectMany(v => v).ToArray()
Reading your question again, I wonder if you're asking how to access a value for a single key. So, if you want the string array for a single key you can simply use the indexer:
var value = _list["keyname"];
But that will cause an exception if the key doesn't exist. If you're not sure that the key exists, you can use .TryGetValue(...):
string[] value;
if (_list.TryGetValue("keyname", out value))
{
// value was found
}
else
{
// value wasn't found
}

casting php arrays to c# hashtables

I have some multi-dimensonial php arrays being passed down to my c# app. To pull values out on the c# side, i have to do something like:
String example = (string)((Hashtable)((Hashtable)example_info["FirstLevel"])["SecondLevel"])["example_value"];
How would I go about removing the need to explicitly cast every dimension as a hashtable? Do I need a recursive function that builds some sort of List object out of example_info, or should I just not be using hashtables?
Here, use this:
public Dictionary<string, object> Parse(string array)
{
Dictionary<string, object> result = new Dictionary<string, object>();
Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(array);
foreach (KeyValuePair<string, Newtonsoft.Json.Linq.JToken> kvp in obj)
{
if (kvp.Value.ToString().Contains('{'))
{
result.Add(kvp.Key, Parse(kvp.Value.ToString().Replace("[", "").Replace("]", "")));
}
else
{
result.Add(kvp.Key, kvp.Value.ToString());
}
}
return result;
}

C# .NET Generate once a string array which his indexes are string values from a table

I have a table contains the columns Title and Info.
I would like to create an array it's index will be the Title, and actual value of the array in that index is the Info in the same row.
So if I have 3 Rows like that:
Title Info
ABC Hi
DEF Sup
GHI Hello
I would like to ask for StringArray["ABC"], and this will return "Hi".
How can I do that?
Thanks Guy
You want a Dictionary<String, String>, not a string array.
var myStrings = new Dictionary<String, String>();
myStrings.Add("ABC", "Hi");
myStrings.Add("DEF", "Sup");
myStrings.Add("GHI", "Hello");
Console.WriteLine(myStrings["ABC"]);
Arrays can only be indexed with an integer. You would have to use Dictionary<string, string>, or some other type that implements IDictionary<string, string>, or you could implement your own type with a string indexer.
Please refer to Dictionary for that
You can do in this way
Dictionary<string, string> Book = new Dictionary<string, string>();
Book.Add("ABC","Hi");
Book.Add("DEF","Sup");
Book.Add("GHI","Hello");
so on and so forth.
So then when you say
Book["ABC"] it will return Hi
You should use dictionary to implement it.
var table = new Dictionary<string,string>(
{"ABC", "Hi"},
{"DEF", "Sup"},
{"GHI", "Hello"}
);
now you can use it
var info = table["ABC"];
you should be careful an exception will be thrown if you use unexisted key
you can use TryGetValue to avoid this exception
string info;
if(!table.TryGetValue("ABC", out info))
{
info = "default value if required";
}

Is there an C# equivalent to the PHP function `parse_str`?

Is there an C# equivalent to the PHP function parse_str?
I couldn't find anything and wrote my own function but is there something in the C# framework?
public Dictionary<string, string> parse_str(string query) {
Dictionary<string, string> data = new Dictionary<string, string>();
foreach(string set in query.Trim('?').Split('&'))
data.Add(set.Split('=')[0], set.Split('=').Length < 2 ? "" : set.Split('=')[1]);
return data;
}​​​​​​
I think you are looking for HttpUtility.ParseQueryString()
If you're taking it from the browser's query string, you can use Request.QueryString
You can get a list of all the keys: Request.QueryString.Keys
Get a value of a key: Request.QueryString["KeyName"]

How to create an array with label and not integer

Suppose I have an array of strings like :
myArray["hello", "my", "name", "is", "marco"]
to access to this variable, I have to put an integer as index. So if I wanto to extract the third element I just do :
myArray[2]
Now, I'd like to use label instead of integer.
So for example somethings like :
myArray["canada"]="hello";
myArray["america"]="my";
myArray["brazil"]="name";
myArray["gosaldo"]="is";
myArray["italy"]="marco";
How can I do this on C#? Is it possible? Thanks
That's called an associative array, and C# doesn't support them directly. However, you can achieve exactly the same the effect with a Dictionary<TKey, TValue>. You can add values with the Add method (which will throw an exception if you try to add an already existing key), or with the indexer directly, as below (this will overwrite the existing value if you use the same key twice).
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["canada"] = "hello";
dict["america"] = "my";
dict["brazil"] = "name";
dict["gosaldo"] = "is";
dict["italy"] = "marco";
C# has a Dictionary class (and interface) to deal with this sort of storage. For example:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("canada", "hello");
dict.Add("america", "my");
dict.Add("brazil", "name");
dict.Add("gosaldo", "is");
Here are the docs: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
With a Dictionary you will be able to set the "key" for each item as a string, and and give them string "values". For example:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canada", "hello");
You're looking for an associative array and I think this question is what you're looking for.

Categories