Share via


Adding 2 arrays into a dictionary as key vlaue pairs c#

Question

Monday, June 8, 2009 3:51 PM

 Hi all

I have 2 string arrays

string[] s1 = new string [20]

string[] s2 = new string [20] 

 

now i want to add the 2  arrays  into  a dictionary<string,string>

dictionary<string,string> d = new dictionary<string,string>();

i want to do some thing like  this 

d.add(s1,s2)

is it possible to do like this i dont want to add each elemnt to a dictionary instead i want to add all at one time.

All replies (4)

Monday, June 8, 2009 7:28 PM ✅Answered

Hi,

I do not know if this is the required, You can do something like this :

 
string[] s1 = new string[20];
string[] s2 = new string[20];
s1[0] = "HII";
s2[0] = "GOO";
Dictionary<string, string> d = new Dictionary<string, string>();
for (int i = 0; i < 20; i++)
{
  if(s1[i]!=null && s2[i]!=null)
  d.Add(s1[i], s2[i]);
}

            // Access the dictionary 
Console.WriteLine(d["HII"]);
 
This approach is good for two arrays of same size. Also this is not a reference copy, it is a value copy.

Monday, June 8, 2009 7:42 PM ✅Answered

This is a bit of a hack...

var count = s1.Select((s,i)=>d[s]=s2[i]).Count();

Some people implement an extension method called ForEach which makes this sort of activity less 'hacky'.


Tuesday, June 9, 2009 4:44 AM ✅Answered

See the code

 Dictionary<string[], string[]> a = new Dictionary<string[], string[]>();
            string[] s1 = new string[20];
            string[] s2 = new string[20];

            s1[0] = "AA"; s2[0] = "LinkedWithS1[0]";
            s1[1] = "AA"; s2[1] = "LinkedWithS1[1]";

            a.Add(s1, s2);

 This is absolutely possible but has no specific meaning I guess, The key should be a unique identifier whereas u want to use a list of string. so eventhough it is possible by adding a string[] into the key the meaning of key get lost. Rather u can create a class for that which contain a stringp[] array and use that class as something like

Dictionary<AClass, BClass>

Soumen, India 

 


Tuesday, June 9, 2009 3:40 PM

 Thank you guys for your reply