How can I convert a dictionary<string, string>
into a number of one dimension integer array at runtime? For example,
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("one", "1,3,6,8");
dic.Add("two", "2,3,6,9");
dic.Add("n", "3,4,1,8");
The desired resulting arrays would be:
int[] arr1 = new int[] {1,3,6,8};
int[] arr2 = new int[] {2,3,6,9};
int[] arrn = new int[] {3,4,1,8};
Could anyone help me to achieve this conversion?
Well for there to be separate variables, you'll need to know all the numbers involved at compile-time. (You can't just generate more variables at execution time... and you really don't want to get into the business of working out the word representations of numbers.) At that point it's fairly easy though:
arr1 = ParseValues(dic["one"]);
arr2 = ParseValues(dic["two"]);
arr3 = ParseValues(dic["three"]);
// etc
static int[] ParseValues(string values)
{
return values.Split(',').Select(int.Parse).ToArray();
}
Note that this will fail with empty strings - if you need it to handle that (returning an empty array) you want:
return values.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
EDIT: If you don't know how many values there will be, but you know they'll always be present with no gaps, you could have:
// This has to go as far as you need to cope with
string[] words = { "one", "two", "three", "four", "five", "six", ... };
List<int[]> arrays = words.TakeWhile(word => dic.ContainsKey(word))
.Select(word => dic[word].Split(',')
.Select(int.Parse)
.ToArray())
.ToList();
(Note that in this list, element 0 will correspond to "one" etc... it'll all be offset by one.)
See more on this question at Stackoverflow