Reputation:
How to assign an array to dictionary in c#
below code is not working
ArrayList conf_list = new ArrayList();
var variations = new Dictionary<string, List<string>>();
conf_list.Add ("hi");
conf_list.Add ("bye");
conf_list.Add ("ss");
conf_list.Add ("fefe");
conf_list.Add ("gg");
conf_list.Add ("qwq");
conf_list.Add ("trt");
variations["available"] = conf_list;
Error:
Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly convert type 'System.Collections.ArrayList' to 'System.Collections.Generic.List<string>' ConsoleApplication1 c:\users\administrator\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 27 Active
How to push hole array at one time to dictionay??
Note: i dont want to use this method
variations["available"] = new List<string> { "hi","bye" };
Upvotes: 0
Views: 109
Reputation: 1603
try this one
List<string> lstString = new List<string>();
var variations = new Dictionary<string, List<string>>();
variations.Add("available", lstString);
if you want to add ArrayList
into Dictionary
so you need to create Dictionary
some thing like ...
var variations = new Dictionary<string, ArrayList>();
Upvotes: 0
Reputation: 43876
You need to convert that ArrayList
into a List<string>
. This can be done like that:
variations["available"] = conf_list.OfType<string>().ToList();
The reason for your error is that conf_list
is of type ArrayList
which is not implicitly convertible to List<string>
.
By using OfType<string>()
you get an enumeration of string
s and with ToList()
you turn this enumeration into an List<string>
which then can be added to your dictionary.
Alternatively you can declare your conf_list
as List<string>
right from the start.
List<string> conf_list = new List<string>();
conf_list.Add ("hi");
//...
Upvotes: 1
Reputation: 33139
Use
var variations = new Dictionary<string, ArrayList>();
or
List<string> conf_list = new List<string>();
The two types can not be used interchangeably.
Upvotes: 1