I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error.
I understand the error, but should it not be possible to assign an array to the second dimension array field?
As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)
string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');
You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].
You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:
string[][] sortedString = new string[count][];
This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.
C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:
string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i++)
sortedString[i] = new string[columns];
Or, even better:
var sortedString = new List<string[]>;
Related
I have a two dimensional array declared. It has two columns - filename and batch. I initialize it empty.
string[,] a_Reports = new string[,] { { "", "" } };
I have some code that resizes it and populates it. Everything is a string value. When I go to look up an element in the array like so:
int value1 = Array.Find<string>(a_Reports, element=>element.Equals(newFileName));
I get the error:
CS1503 Argument 1: cannot convert from 'string[*,*]' to 'string[]'
I've tried it every which way and nothing works. Please help me!!! I've spent hours on it already.
Array.Find is only for one-dimensional arrays. (MSDN)
Check out this answer on 'How do I search a multi-dimensional array?'
Produce a similar extension method, like in my example on rextester.
Or use a jagged array instead of a two-dimensional one and a combination of foreach and find, like:
string[][] jagged = ...
Array.ForEach(jagged, array=>Array.Find(array, x=>x=="" ));
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
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)
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(',');