What will be the C# equivalent of the following ReDim a(0 To i, 0 To 1) ?
I am trying to implement using it by Array.resize ... but it's not working.
Since you aren't using Preserve, this is just:
a = new SomeType[i,1];
More generally Array.Resize (which is akin to ReDim Preserve) only works on vectors (1-dimensional 0-based arrays); there is not an overload for multi-dimensional arrays. You can, however, simply create a new array and then copy the data from the old array to the new array in a loop. However, frankly if you are routinely resizing arrays, then something might be wrong in your code - maybe consider some kind of nested list; or since your second direction is always 0-1, either two separate arrays/lists, or a single array/list of a type with two members.
Related
In C# I'm storing values in an array.
So to create this array I'm using this code, 'int[] values = new int[10];'
But, what if I need more than 10 values, or in the case I never know how many values I will have. Could be 1, 10 or 100.
I understand the idea that I need to let the compiler know how big the array should be so it can allocate memory space for it.
Is there a way to work around that?
You could just use a List and let it do all the heavy lifting for you:
List<int> values = new List<int>();
Arrays must have defined length. If you want dynamic size, consider using List class.
Please take a look at and research the concept of "Immutable objects"
An array has a fixed size, If you need an array with a dynamic size it is best to either create extension methods or a handler that does the work for you.
The work to be done is to get the array, create a new array with the new size based on whether you want to add or remove something, and to populate the new array with the data from the previous array. This will create a new object instead of modifying the previous object and will make sure you don't push items to a full array, or have an array with a size larger than the items that fit in it.
Ofcourse the List class would work as well and would probably solve your problem.
This is the VB6 Code I have
Dim aBcls() As String
ReDim aBcls(0 To iCount, 0 To 1)
For i = 0 To iCount
aBcls(i, 0) = Pick.Extract(sOutput, 1, i + 1)
aBcls(i, 1) = Pick.Extract(sOutput, 2, i + 1)
Next i
I am not able to understand how to convert it to C# Code.
Can someone please guide me on this?
The intent of the VB6 code is to have an array that contains two strings, aka a multi-dimensional array of strings. You can do this either exactly or using a single dimensional array of objects that have two strings (class, struct or tupple).
I would tend towards using using a 1-dimensional array of a class of objects with two strings, unless that conflicts with usage elsewhere.
Note that it uses redim, which you can't do with MD arrays, but from your snippet that was unnecessary. If it is neccesary, you might want to see if you can use a list instead.
Also note that VB6 used ByRef by default, so sOutput could conceivably be changed by pick.extract.
I am trying to create a jagged array but due to the dynamic-ness of the data I am working with I do not want to waste resources creating a a large jagged array.
I am currently doing:
int[][][] data = new data[Int16.MaxValue][][];
I do not how big the data set is, or is there a better way than doing it via Lists?
Yes, you should use List<T>.
In this case, you would use List<List<List<int>>>.
Your array:
int[][][] data = new data[Int16.MaxValue][Int16.MaxValue][Int16.MaxValue];
will take up (2^16)^3 = 2^48 = way more storage space than you have,
not to mention that that declaration is not valid C#.
If you don't know how much space you need when you initialize, then it would be best to use a dynamically resizing list.
Use a variable similar to this:
List<List<List<int>>> data = new List<List<List<int>>>();
This variable allows you to add List<List<int>>'s to it, and those lists contain List<int>'s, which of course contain int's
If you absolutely do not want to use Lists, you can always replicate what Lists do under the hood: Create your array with a small number of elements, and when you reach the maximum, create a new array that is double the original's size, copy your existing array into it, and dispose of your original. Continue this pattern until you are done. I recommend using Lists instead, but this is how you would get around it if, for some reason, you just don't want to use Lists.
In fact, you can create jagged arrays without defining second and further dimensions.
int[][][] jagged = new int[256][][];
But at large datasets it is more effective to use streaming data - i.e., combinations of IEnumerable<T>.
It's easier to write
intArray1.CopyTo( intArray2, 0 )
than the for-loop equivalent, but System.Array does not provide any generic Copy/CopyTo methods.
Is it better to write the for-loop? Or is using Copy/CopyTo compiled or JIT'd efficiently enough?
Array.Copy/CopyTo will perform faster than a manual loop in most cases as it can do direct memory copying.
If you don't have huge arrays or speed is not an issue, use whatever would look best in your code where you need to copy the items.
If you are copying an array of primitive types as your sample would imply, you can us the memory copy technique yourself using the Buffer classes BlockCopy method.
int[] CopyArray(int[] A, int index)
{
const int INT_SIZE = 4;
int length = A.Length - index;
int[] B = new int[A.Length - index];
Buffer.BlockCopy(A, index * INT_SIZE, B,
0 * INT_SIZE, length * INT_SIZE);
return B;
}
This method is the most efficient manner in which to copy an array of primitives. (It only works with primitives)
I say if you know that you want to copy the entirety of the first array to the second array without changing the values or doing any specific processing on the copy, then use Array.CopyTo.
There are some limitations to this. The array must only have a single dimension as I remember it. Also if the arrays are quite large you might have some speed related issues with the copyto, but I would imagine that would only come into play with very large arrays. So, I would try it and test it, but your mileage may vary.
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];