entering and getting values from arrays in one ConcurrentDictionary with C#
-
26-05-2021 - |
Question
Up to this moment I was using simple arrays to enter and get necessary information.
the first example is following:
// ===Example 1. Enter info ////
string[] testArr1 = null;
testArr1[0] = "ab";
testArr1[1] = "2";
// ===Example 1. GET info ////
string teeext = testArr1[0];
// =======================
and the second example:
// ====== Example 2. Enter info ////
string[][] testArr2 = null;
List<int> listTest = new List<int>();
listTest.Add(1);
listTest.Add(3);
listTest.Add(7);
foreach (int listitem in listTest)
{
testArr2[listitem][0] = "yohoho";
}
// ====== Example 2. Get info ////
string teeext2 = testArr2[0][0];
// =======================
But right now I'm trying to assign an identification number to each array, so I could identify multiple different arrays in one ConcurrentDictionary.
How do you Enter and Get info out of array in dictionary?
Look, we have two identifiers and two dictionaries:
decimal identifier1 = 254;
decimal identifier2 = 110;
ConcurrentDictionary<decimal, string[]> test1 = new ConcurrentDictionary<decimal, string[]>();
ConcurrentDictionary<decimal, string[][]> test2 = new ConcurrentDictionary<decimal, string[][]>();
I was imagining something like this:
//////////Example 1
//To write info
test1.TryAdd(identifier1)[0] = "a";
test1.TryAdd(identifier1)[1] = "b11";
test1.TryAdd(identifier2)[0] = "152";
//to get info
string value1 = test1.TryGetValue(identifier1)[0];
string value1 = test1.TryGetValue(identifier2)[0];
//////////Example 2
//To write info: no idea
//to get info: no idea
P.S.: The code above doesn't work (since it's self-made).. so what's the right way to enter information into string[] and string[][] in ConcurrentDictionary by an ID? (and to get it out)
Solution
Given your declarations
decimal identifier1 = 254;
decimal identifier2 = 110;
ConcurrentDictionary<decimal, string[]> test1 = new ConcurrentDictionary<decimal, string[]>();
ConcurrentDictionary<decimal, string[][]> test2 = new ConcurrentDictionary<decimal, string[][]>();
you can use code like this
test1[identifier1] = new string[123];
test1[identifier1][12] = "hello";
test2[identifier2] = new string[10][];
test2[identifier2][0] = new string[20];
test2[identifier2][0][1] = "world";
to enter your data. Here's an example of accessing the data you entered:
Console.WriteLine(test1[identifier1][12] + " " + test2[identifier2][0][1]);
I must say, though, that such code tends to be quite convoluted and difficult to debug, especially for the test2 case. Are you sure you want to use jagged arrays?