How is an array of string where you do not know where the array size in c#.NET?
String[] array = new String[]; // this does not work
Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>
List<String> list = new List<String>();
list.Add("Hello");
list.Add("world");
list.Add("!");
Console.WriteLine(list[2]);
Will give you an output of
!
MSDN - List(T) for more information
You don't have to specify the size of an array when you instantiate it.
You can still declare the array and instantiate it later. For instance:
string[] myArray;
...
myArray = new string[size];
You can't create an array without a size. You'd need to use a list for that.
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:
String[] s = yourListOfString.ToArray();
I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:
List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");
Or, if you need to be absolutely sure that the strings remain in order:
Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");
Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.
I suppose that the array size if a computed value.
int size = ComputeArraySize();
// Then
String[] array = new String[size];
Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
If you want to use array without knowing the size first you have to declare it and later you can instantiate it like
string[] myArray;
...
...
myArray=new string[someItems.count];
string[ ] array = {};
// it is not null instead it is empty.
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');
Related
string[] SalesReferenceArray = {};
int i=0;
if (chk_Select.Checked == true)
{
SalesReferenceArray[i] = Convert.ToString((Label)grdSales.FindControl("lblSalesReference"));
i++;
}
Index was outside the bounds of the array while assigning label to array
string[] SalesReferenceArray = {};
Your array is empty, i.e. it does not have any items. Trying to access first item (i.e. item at index 0) gives you IndexOutOfRange error, because index of item should be non-negative and less than array length.
If you need to have only one item, then you don't need array at all. Just declare variable of string type:
string SalesReference;
If you want to add/remove items dynamically then use list instead of array:
List<string> SalesReferences = new List<string>();
if (chk_Select.Checked) // don't compare with true
{
string reference = Convert.ToString((Label)grdSales.FindControl("lblSalesReference"));
SalesReferences.Add(reference);
}
NOTE: I think you need to use Label.Text instead of trying to convert label to string.
You are creating an empty array with 0 size, i.e. you are using the short-hand assignment syntax and not specifying any elements.
You will need to fix your code by changing it to specify a size, like so:
string[] SalesReferenceArray = new string[10]; // creates an array with 10 empty elements
If you don't know the size of your array in advance, you might want to use a List instead:
List<string> salesReferenceList = new List<string>();
if (chk_Select.Checked == true)
{
salesReferenceList.Add(Convert.ToString((Label)grdSales.FindControl("lblSalesReference")));
}
A list would be more appropriate for you as it's dynamic.
List<string> SalesReferences = new List<string>();
then add to it like...
SalesReferences.Add("Hello World");
So I have some code which stores some data in an array. When new data comes in it is put in a new array item (The totalnumber of array items) then the total number of array items is added too ready for the next bit of data. But when I try to add data into the array, be it array[0] or whatever it throws array index out of bounds?
Declaration:
string[] TabMessages = { };
int TotalTabs = 0;
Using it:
DevComponents.DotNetBar.TabItem Tab = TabStrip.CreateTab(TabName);
Tab.Tooltip = id + "|" + TabIndex;
TabMessages[TotalTabs] = "";//index out of bounds of array
TabStrip.SelectedTab = Tab;
TotalTabs++;
Any help, this is really annoying me because it's throwing the error about the index being out of bounds of the array when I'm trying to create a new entry to the array...
Arrays are a static length. You have defined an array of 0 length, then tried to access an element in the array that does not exist. Either you have to create a large enough array to hold all of the values you intend to use, or use a non-static collection like List<string> instead of a static-sized one like string[].
List<string> TabMessages = new List<string>();
TabMessages.Add("");
If you want something you can access by index, but don't want to supply all possible values, use a dictionary:
Dictionary<int, string> TabMessages = new Dictionary<int, string>();
TabMessages[TotalTabs] = "";
Arrays in C# are not dynamic - they are fixed size. Try using something list a List<string> and using the Add method to insert a new entry into it.
TabMessages is an array of 0 elements (that's how you declared it). As such, you won't be able to add (or set) any element on it - you'll get an index out of bounds exception every time.
This code:
string[] TabMessages = { };
is equivalent to:
string[] TabMessages = new string[0];
it means you created array which size 0. That is why you got this kind of exception. So you can use List<string> instead with dynamic size:
var TabMessages = new List<string>();
Then you can add the first item:
TabMessages.Add(string.Empty);
Or, create string array with fixed size depending on your business rule:
string[] TabMessages = new string[5]; // create string array with 5 elements
Array's are defined as having a fixed size. Declaring string[] TabMessages = {} is the same as string[0] Tabmessages;
You can resize an array (but I think it is a moderately expensive process) - see http://www.dotnetperls.com/array-resize
Alternatively (and preferably), try using some type of List construct
When using the .ToArray() function is it necessary to implicitly define the size of the array in order to hold of the characters that were in the list you're converting?
String [] array = List.ToArray();
I tried doing this because I needed to use the .GetValue() ability of the array, however, the array is maintaining a size of 1 and not holding the material from the list. Am I trying to use the .ToArray() incorrectly?
colAndDelimiter = new List<string>();
colAndDelimiter.Add(text);
String [] cd = colAndDelimiter.ToArray();
This is all of the code I have that effects the array. When I Console.WriteLine() the list it gives me the entirety of the text. I may be confused about how list works. Is it storing everything as a single item, and that's why the array only shows one place?
You don't need to convert it to an array to get specific characters out.
Just use text[index] to get at the needed character.
If you really need it as an array, use String.ToCharArray() - you want an array of char not an array of string.
Edit:
Is it storing everything as a single item, and that's why the array only shows one place?
Yes, yes it is. You're making a list of strings which contains one string: the entire contents of text - what it seems that you want is to split it up letter by letter, which is what the above methods will achieve.
It should work fine, but try the var operator to be sure.
var array = List.ToArray();
Is there a reason to use Array.GetValue instead of the built in functions of the List<T> itself
EG:
string value = List.ElementAt(1);
var values = List.GetRange(0, 5);
What you are doing is fine.. but lets say that you are not sure of the size of the
string[] cd then you can do something like the following
var colAndDelimiter = new List<string>();
colAndDelimiter.Add(text);
String[] cd = { };
cd = colAndDelimiter.ToArray();
find the position of the data in cd
string value = cd[0];
Update:
If you want to do this based on values being stored in a single line then you can do this without having to declare the cd variable as string[] cd;
var colAndDelimiter = new List<string>();
colAndDelimiter.Add("Hello, World, Week, Tuesday");
var cd = colAndDelimiter[0].Split(',');
As long as your List object is some IEnumerable (or similar) that has items in it, this should indeed convert your List to an Array.
Note that once you have created this array, adding elements to List won't also add it to the Array
I have an array:
String[] ay = {
"blah",
"blah number 2"
"etc" };
... But now I want to add to this array at a later time, but I see no option to do so. How can this be done? I keep getting a message saying that the String cannot be converted to String[].
Thank you
Use a List rather than an array:
List<string> list = new List<string>();
list.Add( "blah" ) ;
Then, later, if you really do need it as an array:
string[] ay = list.ToArray();
Arrays are of fixed size, so after it has been created, you can't change the size of it (without creating a new array object)
Use the List<string> instead of the array.
Arrays can't change their size after they are declared. Use collections instead. For example: List.
As everyone's already said, use List in the System.Collections.Generic namespace.
You could also use a Hashtable which will allow you to give each string a meaning, or "key" which gives you an easy way to pull out a certain string with a keyword. (as for keeping messages stored in memory space for whatever purpose.)
You could also Create a new array each time you add a value, make the new array 1 bigger than the old one, copy all the data from the first array into the 2nd array, and then add your new value in the last slot (Length - 1)
Then replace the old array with your new one.
It's the most manual way of doing it.
But List and Hashtable work perfectly well too.
If you don't need indexing a specific array element (usage of brackets), but you want to be able to efficiently add or remove elements, you could use LinkedList.
If you do need indexing
have a look at Dictionary data type also in the System.Collection
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
so you could do something like
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "afljsd");
You can do this but I don't recommend it:
// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
// oldArray the old array, to be reallocated.
// newSize the new array size.
// Returns A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
System.Array.Copy (oldArray,newArray,preserveLength);
return newArray;
}
Here's an extension method to add the to arrays together and create a new string array
public static class StringArrayExtension
{
public static string[] GetStringArray (this string[] currentArray, string[] arrayToAdd)
{
List<String> list = new List<String>(currentArray);
list.AddRange(arrayToAdd);
return list.ToArray();
}
}
I want to define an array of strings but I don't know the number of strings I'll need to store in it. Can I define such an array, and how can I insert strings into it?
Better use List like this:
List<string> names = new List<string>();
names.Add(name); ///whatever string you want to insert
Later if you need array of names, call:
string[] arr = names.ToArray();
If you have to use an array of strings then you should know the size upfront. If you don't know the size, then you can initialize array of some default length (say 10).
The things that you have to do are:
Keep the count of strings already added in array
If it reaches the default length, you have re-initialize the array with a bigger length (say 15) and copy all existing strings to this new array.
You have to keep checks of the boundaries of this array, you don't want to read from indexes you haven't used yet (i.e. if the index is greater then count)
So its better to use list rather then doing all this stuff by yourself
You can use a List<string>, this will expand as you add items to it.
List<string> myList = new List<string>();
myList.Add("string1");
myList.Add("string2");
It can easily be converted to an array if needed:
string[] stringArray = myList.ToArray();
If you don't know the exact number of items you will need, an array may not be a good choice, as you will need to resize it (which is an expensive operation).
I would use the List class. You can add as much as you need without having to know how much you're going to put in there. If you do have some idea as to how much will be going in the list, you can use the capacity argument of List's constructor to prevent performance problems.
int capacity = 3;
var listOfNames = List<string>(/* optional */ capacity);
listOfNames.Add("My Name 1");
listOfNames.Add("My Name 2");
listOfNames.Add("My Name 3");
var namesArray = listOfNames.ToArray();
I added the namesArray line in there in case you really needed an array instead of a List for some reason.
See this page to see what all you can do with a List.
You can use the following, as Oded mentioned above (or below), it will auto expand when items are added to it.
List<String> l = new List<String>();
l.Add("your string here");
...And if you'd like to iterate, then:
foreach(string i in l)
{
// Do something with each item (i);
}
...And to have an Array:
String[] a =
l.ToArray();
Use List<T>. E.g.
var list = new List<string>();
list.Add("string1");
if you need the list to be an array, List<T> has a ToArray() method.
Internally List<T> stores the data as an array of strings. When more space is required, it will allocate a new array of double the size of the current and copy all the references to the new array. I.e. you don't have to do anything, but if the code is performance critical, you may want to supply a default capacity when creating the list.
ArrayList will do the trick too.
ArrayList alist = new ArrayList();
alist.Add(String1);
alist.Add(String2)