This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
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?
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();
You have to initialize the string array.
string[] txtArr = new string[dataList.Count];
Related
This question already has answers here:
List<T>.ForEach with index
(12 answers)
Closed 4 years ago.
I'm need to call function from ForEach in Linq, and I need to send a string parameter and the Index from the ForEach
List<string> listString= new List<string>();
listString.ForEach((str, i) => { Func(str, i) , i++});
private ResponseBase Func(string s,int i)
{
You could try something like this:
var responses = listString.Select((value, index) => Func(value, index)).ToList();
The above for each item in listString would call the method you have defined. The results of all calls would be stored in a list and you could access them by using the corresponding index.
I'm a big fan of LINQ. Really.
But in this cases, when you are accessing an already existing List, I would go for an old fashioned for loop.
for(var i = 0; i < listString.Count; i++)
Func(listString[i], i);
It's not longer, it's far more efficient (it's probably not a problem, but let's remember this), and it just gets the job done.
You can introduce a variable and then increment it:
List<String> values = new List<String>();
int indexTracker = 0;
values.ForEach(x=> { Func(x, indexTracker++); });
Or you can write the following extension method:
public static void ForEach<T>(this List<T> input, Action<T, int> action)
{
for(int i = 0; i < input.Count; i++)
{
action(input[i], i);
}
}
and then use it like
values.ForEach((x,i)=> Func(x, i));
This question already has answers here:
Convert array of integers to comma-separated string
(5 answers)
Closed 6 years ago.
I have managed to get a list of names from a database, join the first and last name, put these names into an array so that they can be called up in say a MessageBox. How do I place the values from a dynamic string array into a string variable preferably separated by commas.
Here is my code so far:
string[] array = new string[size];
for (int i = 0; i < size; i++)
{
array[i] = Join(fullname);
}
foreach (string i in array)
{
MessageBox.Show(i);
}
Use string.Join:
var myString = string.Join(",", array);
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
int count = 0;
foreach (string s in Settings.Default.Name)
{
count++;
}
Settings.Default.Name[count] = tb_add_name.Text;
Settings.Default.Save();
Settings.Default.Name is an empty string array but should the foreach - method just dont start if the string array is empty instead of giving me this error?
The array will be filled with words later.
Yes, but that won't change the fact that count is still 0 and you still execute
Settings.Default.Name[count] = tb_add_name.Text;
So you should still check if the index is Valid or null. Something like:
if(Settings.Default.Name != null && Settings.Default.Name.Count > 0)
By the way, your method will always lead to an IndexOutOfRange exception because your foreach loop basically sets your count variable to the size of the Array, and Array[Array.Length] is always out of range.
You can use Array Length property.
if(Settings.Default.Name.Count > 0)
{
int count = 0;
foreach (string s in Settings.Default.Name)
{
count++;
}
Settings.Default.Name[count] = tb_add_name.Text;
Settings.Default.Save();
}
This question already has answers here:
Convert an array to dictionary with value as index of the item and key as the item itself
(3 answers)
Closed 7 years ago.
is there any better way of this code
var dictionary= new Dictionary<int,object>();
int x=0;
foreach( var item in SomeCollection)
{
x++;
dictionary.Add(x,item);
}
Whats the best practice ? Can we avoid declaring int x=0; and get the current iteration value ??
Certainly a for loop. Optionally you could use LINQ:
int temp = 0;
var dict = SomeCollection.ToDictionary(_ => ++temp, item => item);
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
how to inset a new array to my jagged array
i have a problem, where i dont know how i can make a string array variable in array length.
i have this code now below:
string[] p = new string[10];
int num = 0;
foreach (Product products in GetAllProducts())
{
//do something
p[num]= "some variable result"
num++
}
The problem is, that i dont know how many of "p" i will get, although i know it atleast will be less than 10.
but if i put it on 0, i will get an error when i start it, because it doesn't know the "p[num]"
So i am looking for some way to make "p" have a variable length.
anyone could help me out a bit? thanx
============Solved==========
List<string> p = new List<string>();
int num = 0;
foreach (Product products in GetAllProducts())
{
string s= null;
//do something ( create s out of multiple parts += s etc.)
p.add(s)
num++
}
thanx to solution poster
Use an List<string> instead of an array, if you do not know the number of items you will need to add.
Your array length cannot be modified after it has been instantiated. Use ArrayList or Generic Lists.
var p = new new List<string>(10);
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
What does GetAllProducts() return? Does it have a count or a length?! You should call that first, save it in a variable, get the count/length and then declare your array!
There's two solution.
If you want to keep using array :
int num = 0;
var list = GetAllProducts();
string[] p = new string[list.Length]; // Or list.Count if this is a collection
foreach (Product products in list)
{
//do something
p[num] = "some variable result";
num++;
}
Otherwise you should use a List like this :
List<string> p = new List<string>();
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
Use Array.Resize() method, which allows to resize it (by n number of indexes).
In my exmaple I will reize by 1 on each step of the way:
string[] array = new string[3]; //create array
for (int i = 0; i < 5; i++)
{
if (array.Length-1 < i) //checking for the available length
{
Array.Resize(ref array, array.Length + 1); //when to small, create a new index
}
array[i] = i.ToString(); //add an item to array[index] - of i
}
Because your code is using a foreach on the result from GetAllProducts, then GetAllProducts must be returning a IEnumerable collection. Probably the best solution would be to simply assign the result of GetAllProducts to such a collection. For example, perhaps it already returns a list of strings? So you can do:
List<string> strings = GetAllProducts();
There is no need to have a foreach loop to create an array when you already have a collection anyway being returned from GetAllProducts.
Or simply:
var strings = GetAllProducts();
to let the compiler work out the type of strings.
Most things you can do with an array you can also do with a List, and some more (such as adding items to the end of the List).
Perhaps you can post the signature of GetAllProducts (especially its return type) so we can better advise you?
I see many gave you the right answer which is the use of Lists. If you still need an array in the end, you can easily convert your list into an Array like this :
string[] tempArray = myList.ToArray();