-3

I have IDictionary<string, int>. I need to get keys and values from dictionary in string format and add into string[] array. I need to do it because I want to pass that text in function and that function takes string array. I have that code for getting value:

foreach (KeyValuePair<string, int> kvp in dict)
{
    dataList.Add(kvp.Key + " " + kvp.Value.ToString());
}

I've created list and add in that list keys and values. After I was thinking to create for loop and from list add elements into array, but have error. Loop:

string[] txtArr;
for (int i = 0; i < dataList.Count; i++)
{
    txtArr[i] = dataList[i];
}

Error: System.NullReferenceException. I don't understand where is the problem. From what I read about that error, I understood it raised because something is null. But if I'm trying print in console dictionary or list all is OK, there isn't null, also i is int and = 0. Where is the problem?

ASh
  • 30,500
  • 9
  • 48
  • 72
sb69lg
  • 15
  • 1
  • 6

2 Answers2

3

Your array is not instantiated, dude:

string[] txtArr = new string[dataList.Count];
for (int i = 0; i < dataList.Count; i++)
{
  txtArr[i] = dataList[i];
}

or you can do it like this:

string[] txtArr = dataList.ToArray();

or you can do it like this:

string[] txtArr = dict.ToList().Select(x => x.Value).ToArray();
Amir
  • 771
  • 4
  • 7
  • Thank you, dude :) – sb69lg Jan 28 '21 at 16:11
  • Anytime :). Mark it as true if you found it useful, please. – Amir Jan 28 '21 at 16:12
  • Why the call to `ToList`? You are taking a dictionary, making a copy of it as a `List>` and then eventually taking this to create an array with the `ToArray` call. No a problem if the initial collection is small, but serious if you have a large collection to start – Flydog57 Jan 28 '21 at 16:19
  • Yes. You are right, the third answer can have some performance issues on large collections. – Amir Jan 28 '21 at 16:23
2

You have to initialize the string array.

string[] txtArr = new string[dataList.Count];