Dictionary : search in a string for dictionary values - c#

I want to search in a given string, if it startsWith any of the values in a dictionary :
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary .Add("ab1", "]0" );
dictionary .Add("a2", "]E");
dictionary .Add("bc3", "]f");
and a string testString ="]0L256984523";
in this case it would return true.
Any suggestion?
Thanks !

Related

get a value of a specific key in a dictionary in C#

I have a dictionary like this:
Dictionary<string, List<string>> mydict = new Dictionary<string, List<string>>();
I have tried:
foreach(var value in mydict.Keys)
{
List<string> key
key.Add();
}
I believe this is wrong to get a specific key value
You have a Dictionary<string, List<string>>. A dictionary have a key and a value. In your case, the key is a string and the value is a List<string>.
If you want get the value of a concrete key, you can use:
myDict.TryGetValue("TheValueToSearch", out List<string> list)
TryGetValue return true when the key is in the dictionary. So you can do:
if (myDict.TryGetValue("TheValueToSearch", out List<string> list))
{
// Do something with your list
}
You can access directly to the list using myDict["TheValueToSearch"] but you get an exception if the key isn't in the dictionary. You can check if exists using myDict.ContainsKey("TheValueToSearch").
To iterate all dictionary values:
foreach(var key in mydict.Keys)
{
List<string> values = mydict[key];
// Do something with values
}
Apart from that, in the concrete case of a dictionary having a string as a key, you can use an overloaded constructor if you want that key will be case insensitive:
new Dictionary<string, List<string>>(StringComparer.CurrentCultureIgnoreCase)

How to declare array of strings with string index?

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
}

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";
}

Add an Array to a Dictionary in C#

I have tried reading the other posts on this subject and can't quite figure this out.
I have a list in C# that I want to put in a dictionary with all of the same keys. The list is this
string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};
I want to create and populate a dictionary with the key being "IN" (the name of the array) and then having each string for the array in the dictionary.
This is what I wrote to create the dictionary (which I am not sure is correct):
Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()
But I am not sure how to populate the dictionary.
Any help would be greatly appreciated as this is the first time I have tried to use a dictionary and I am new to C#
An array is string[], not List<string>, so just do this:
Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();
Now you can add your array as usual.
wordDictionary.Add("IN", IN);
Or:
wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});
Dictionary.Add("IN", new List<string>(IN));
...if you want to keep the current signature for your dictionary.
If you change it to Dictionary<string, string[]> then you can just:
Dictionary.Add("IN",IN);
You currently have a string array, not a list - so it should be:
Dictionary<string, string[]> wordDictionary = new Dictionary<string,string[]> ()
Then you can just add items like:
wordDictionary.Add("IN" , IN);
Do you really need to convert your array into a string? You could very well use string[] instead of List in your dictionary:
var wordDictionary = new Dictionary<string, string[]>();
wordDictionary.Add("IN", IN);
But if you really want to convert your string array to List:
var wordDictionary = new Dictionary<string, List<string>>();
wordDictionary.Add("IN", IN.ToList());
Another way to add the array (it's not a list) to the dictionary is to use collection initializer:
var wordDictionary = new Dictionary<string, string[]> { "IN", IN };
This is exactly the same as creating the dictionary in a normal way and then calling Add("IN", IN).

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