I have declaration as follow:
IList<int[]> populacja = new List<int[]>();
but I want to declare also a constant size of int table. So I want something like this
IList<int[2]> populacja = new List<int[2]>();
How to do that? What is a good solution for making list of int table ?
If it's important for you to ensure that populacja is always int[2], you can wrap it in a class, then make a list of that class. Built in options include Tuple, for example:
IList<Tuple<int,int>> populacja = new List<Tuple<int,int>>();
Just an FYI.
The reason you cant declare int[2] in IList is because it is expecting a type. In this case, the type is an array of int (int[]). The T doesn't care about the length or anything like that. If you did want to use int[] you will need to do something like this --
IList<int[]> populacja = new List<int[]>();
populacja.Add(new int[2]); // empty int array of size 2
populacja.Add(new [] { 3211,3212 }); // non-empty int array of size 2
Every time you add a new array of int, you will need to explicitly instantiate it with a size of 2 since there is no constraint.
Related
Okay, I'll caveat this question with two things. One, I'm not as smart as you (I'm really not). Second, I may have found an answer to my own question, but want to verify.
I'm attempting to declare multiple arrays at the same time. It looks something like this. The first is just declaring a single array, while the second tries to declare both profit_Normal and profit_High in the same line:
double [] tradeType_Active = new double [15];
double [] profit_Normal, profit_High = new double [5];
Can I do this? I currently use this syntax for declaring non-array values with commas, like this:
double
BUpper,
BUpper_Prev,
BUpper_Prev2;
Please let me know when you have a moment.
Your line of code
double[] profit_Normal, profit_High = new double[5];
does declare multiple double[]. What it doesn't to is to initialize all of them. It initializes only the second one.
If you have the following line:
double[] a, b, c, d = new double[5];
what happens is that you are declaring 4 references of arrays of double. For each array you declare you must initialize it - which you are doing only for the last.
To initialize multiple arrays you need to actually initialize them:
double[] profit_Normal = new double[5], profit_High = new double[5];
The difference between the arrays case and this double BUpper, BUpper_Prev, BUpper_Prev2; is that arrays are reference types that their default value is null and must be initialized, whereas doulbe's default value is 0.
Yes, this is absolutely allowed, as long as you keep [] in the declaration to indicate that you are declaring an array:
double[] a = new double[4], b = new double[5];
The double[] part is the type of variables being declared. In your case, that's an array of double.
Note that the only difference between the above and your second declaration is that you did not initialize the profit_Normal variable.
You can use the same syntax you currently use, but in order to instantiate each one as well as declaring it, it would look like this, with = new double[5] after each one:
double[]
profit_Normal = new double[5],
profit_High = new double[5];
I am just beginning with programming in c#;
I got a list of int variables that I want to sort, and find the number 1.
int Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9
do I need to do this with an array?
By using the yellow book of C# I found out how to make an array, but I can't figure out how to assign the variables to the array.
int [] Weapon_Count = new int [11] ;
for ( int i=0; i<11; i=i+1)
{
Weapon_Count [i] = ??? ;}
I hope this does make sense..
Please let me explain how to use a C#-array.
This creates an unitialized integer-array with 5 elements:
int[] a1= new int[5];
Assigning values 9,8,7,6 and 5:
(Please note that only indexes from 0 to 4 can be used. Index 5 is not valid.)
a1[0]=9;
a1[1]=8;
a1[2]=7;
a1[3]=6;
a1[4]=5;
The same can also achieved with just one line:
int[] a1= new int[] {9,8,7,6,5};
This might help you.
// Declaring the array
int[] Weapon_Count;
// Initializing the array with a size of 11
Weapon_Count = new int[11];
// Adding values to the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Weapon_Count[i] = i + 100;
}
// Printing the values in the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Console.WriteLine(Weapon_Count[i]);
}
// Same thing with a list
// Daclare and initializing the List of integers
List<int> weapon_list = new List<int>();
// Adding some values
weapon_list.Add(1);
weapon_list.Add(2);
weapon_list.Add(3);
weapon_list.Add(4);
weapon_list.Add(5);
// Printing weapin_list's values
for (int i = 0; i < weapon_list.Count; i++)
{
Console.WriteLine(weapon_list[i]);
}
// This is just for the console to wait when you are in debug mode.
Console.ReadKey();
Dont forget to include the using statment if you want to use lists (in short hand - dynamic arrays that can change in size.)
using System.Collections.Generic;
The easiest way to do this, assuming there is a finite list of variables to check, would be to throw them into a temporary array and call either Max() or Min() from the System.Linq namespace.
int maxCount = new int[] { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 }.Max(); // or .Min()
EDIT
If you still want to get those variables into an array, I would recommend using a System.Collections.Generic.List which has a dynamic size and helper methods such as .Add() to simplify things. Lists can also be used with Linq functions similar to the first part of my answer. See Dot Net Perls for some really good examples on different C# data types and functions.
EDIT 2
As #kblok says, you'll want to add using System.Linq; at the top of your file to gain access to the functions such as Max and Min. If you want to try using the List type, you'll need to add using System.Collections.Generic; as well. If you're in Visual Studio 2017 (maybe 2015 as well?) you can type out the data type and then hit Ctrl + . to get suggestions for namespaces that might contain that data type.
Before we start, you might edit your array to look like this:
int[] weapons = { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 };
This means that you've created an array called weapons and it is holding integer values.
After you did this, lets find out which element in your array has value of number one.
To find which value has value "1" we must look at each element in array, and we might do that on few ways but I would like recommend foreach or for loop, in this case I will choose foreach loop.
foreach(var item in weapons)
{
if (item == 1)
//Do something
}
This above means, loop throught all of my elements, and in case some of them is equal to number one please do something..
P.S
(I may advice to create one variable which will hold an element which has value '1' and when you find it in a loop assing that variable to that element, and later you can do whatever you want with that variable.. and if you think there will be more elements with value of number one and you need all of them, instead of variable I mentioned above you will create list or array to hold all of your elements and also you can do later with them whatever you want to.)
Thanks and if you are interested in this kind of solution, leave me a comment so let me help you till the end to solve this if you are still struggling.
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();
}
}
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(',');