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#.
Related
I need to map one string (sentence) in to two lists (similar sentences indexes and the different word in each one).
By using "Dictionary" I have to use 2 dictionaries to save each list.
Is there other way to save a string as a key to int[] and string[]?
this is how it lookes now:
Dictionary<string, int[]> similarSentences = new Dictionary<string, int[]>();
Dictionary<string, string[]> changes = new Dictionary<string, string[]>();
I want someting like this:
Dictionary<string, int[],string[]> similarSentencesAndChanges = new Dictionary<string, int[],string[]>();
Thank you!
You could use tuples:
Dictionary<string,(int[] Similar, string[] Changes)> similarSentencesAndChanges = new Dictionary<string,(int[] Similar, string[] Changes)>();
and then you can access it like this:
var someKey = "somekey";
(int[] similar, string[] changes) = similarSentencesAndChanges[someKey];
However, depending on what you plan to do, randomly using tuples is a bad practice and you'd be wise in creating a class that contains both collections.
class SentenceData
{
public int[] Similar {get;}
public string[] Changes {get;}
}
Then, make your dictionary of type Dictionary<string, SentenceData>.
This has the added benefit of allowing the reuse of the object in other parts of your code. Furthermore, adding properties to the object at a latter stage won't involve potentially rewriting large parts of your code.
Assuming you are ok to use tuples, you could create an extension method for the generic Dictionary<TKey, TValue> type, which returns a dictionary with tuple values...
public static Dictionary<TKey, (TValue, TValue2)> Combine<TKey, TValue, TValue2>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue2> b)
{
return a.Keys.Union(b.Keys).ToDictionary(x => x, x => (
a.ContainsKey(x) ? a[x] : default,
b.ContainsKey(x) ? b[x] : default
));
}
Example usage...
var similarSentencesAndChanges = similarSentences.Combine(changes);
I am looking to dynamically create tuples of a given size that have all the same type.
So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>
I have tried both to pass strings into the angle brackets for Tuple like this:
string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
and to pass an array of types into the angle brackets like this:
List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
Neither one of these worked. Does anyone know how to make the described dynamic tuples?
(The reason I want to do this is to use tuples inside of a dictionary like
Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have
Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
{testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);
it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)
You could do something like this using reflection:
public static object GetTuple<T>(params T[] values)
{
Type genericType = Type.GetType("System.Tuple`" + values.Length);
Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
Type specificType = genericType.MakeGenericType(typeArgs);
object[] constructorArguments = values.Cast<object>().ToArray();
return Activator.CreateInstance(specificType, constructorArguments);
}
That will give you a tuple for a variable number of elements.
"Does anyone know how to make the described dynamic tuples?"
You can just use Tuple.Create(). For a 3-tuple:
var tupleOfStrings = Tuple.Create("string1", "string2", "string3");
var tupleOfInts = Tuple.Create(1, 2, 3);
Make custom type with List<string> inside (or List<T> if you want generic solution)
Override object.Equals: Use Enumerable.SequenceEqual for inner list in your custom class
Override object.GetHashCode() in order to use your type in dictionary
How can I read the value from SortedList when I have this structure in Hashtable ?
Below is the example
public SortedList sl = new SortedList();
sl[test] = 1;
Hashtable ht= new Hashtable();
ht.Add("root", sl);
I want to read the sl[test].
You just do the reverse:
SortedList sortedList = (SortedList)ht["root"];
object value = sortedList[test];
As it stands, you will need to cast the result of the hash table back to a SortedList before you can use methods such as the indexer on it, requiring this kind of ugliness:
var result = (ht["root"] as SortedList)[test];
However, if all elements of your hashtable are SortedLists, you can use a generic container such as a Dictionary instead, to avoid the casting:
var dic = new Dictionary<string, SortedList> { { "root", sl } };
result = dic["root"][test];
And you might also consider replacing the SortedList with its generic counterpart, e.g. SortedList<string, int> (depending on the type of 'test'), for the same reasons.
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);
What I just want is to initialize a string[] array constant by specifying not only the values, but the indexes they will be attached to.
For example, on:
private static readonly string[] Pets = new string[] {"Bulldog", "GreyHound"};
I would like to state that BullDog corresponds to index 29 and GreyHound to 5 (Like php :) )
Any suggestion?
Cheers,
If you have some flexibility in terms of your data structure, it would be more efficient to use a Dictionary<int, string> instead of an array for this behavior.
Example (if you are using C# 3 or above):
var pets = new Dictionary<int, string> {
{ 29, "Bulldog" },
{ 5, "Greyhound" }
};
Console.WriteLine(pets[5]);
Same example for legacy applications:
Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);
It sounds like you don't want an array, but a Dictionary<int, string> instead, which could be initialized like this:
private static readonly Dictionary<int, string> pets =
new Dictionary<int, string> {
{ 29, "Bulldog" },
{ 5, "Greyhound" }
};
(Note that this collection initializer syntax was only added in C# 3. If you're using an older version you'll have to call Add or the indexer explicitly multiple times.)
You can access a dictionary via its indexer which looks like array access:
string x = pets[29];
pets[10] = "Goldfish";
I don't think what you want is possible in C# when declaring arrays.
Besides using a Dictionary as others have suggested, you could try using an enumeration instead, with values corresponding to your specific array indices and descriptions (using the Description attribute) corresponding to the string values.
private enum Pets
{
[Description("GreyHound")]
Greyhound = 5,
[Description("Bulldog")]
Bulldog = 29
}
For the record, I agree with everyone that a Dictionary is probably more appropriate. But you can write a little method to pull off what you want:
public static T[] CreateArray<T>(params Tuple<int, T>[] values)
{
var sortedValues = values.OrderBy(t => t.Item1);
T[] array = new T[sortedValues.Last().Item1 + 1];
foreach(var value in sortedValues)
{
array[value.Item1] = value.Item2;
}
return array;
}
And call it like this:
string[] myArray = CreateArray(new Tuple<int, string>(34, "cat"), new Tuple<int, string>(12, "dog"));
If C# receives the syntactic sugar for Tuple that many people seem to want, this would get a tad cleaner looking.
Is this a good idea? Almost certainly not, but I'll leave that for the OP to judge.
You can not do that in the initializer, you need to first specify the size of the array and then add items at specific locations.
private static readonly string[] Pets = new string[42];
and then in a static constructor you insert your items.
private static MyClass
{
Pets[29] = "Bulldog";
Pets[5] = "Greyhound";
}
But as other have suggested: use the Dictionary<int, string>.
You don't need a string array, but instead a Dictionary.
Take a look at link text, there's a fine example there (which I adapted here):
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(2, "cat");
d.Add(1, "dog");
d.Add(0, "llama");
d.Add(-1, "iguana");