Is there any method for creating a dynamic array in C#?
Take a look at Generic Lists.
Expanding on Chris and Migol`s answer with a code sample.
Using an array
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)
In this case you may use the ToArray() method after initiating your List dynamically
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
Of course, this has sense only if the size of the array is never known nor fixed ex-ante.
if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)
List<T> for strongly typed one, or ArrayList if you have .NET 1.1 or love to cast variables.
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array.
Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed
Dynamic Array Example:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
This answer seems to be the answer you are looking for Why can't I do this: dynamic x = new ExpandoObject { Foo = 12, Bar = "twelve" }
Read about the ExpandoObject here https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx
And the dynamic type here https://msdn.microsoft.com/en-GB/library/dd264736.aspx
Related
Pre-information
-User inputs data in console
-Save data in an Array of 2 elements[2]
-Save the Array with 2 elements in a LIST
*Now what i try to achieve is that the user can check if search is in the list regardless if its written in lower or upper case.
List<string[]>MyList = new List<string[]>();
var[] myArray = new [] { "A", "B" };
MyList.Add(myArray);
int y = 0;
Console.WriteLine("Inpu what you are Searching For: ");
string serchString = Console.ReadLine();
serchString = serchString.ToLower();
for (int i = 0; i < MyList.Count; i++)
{
List<object> oneTimeList = new List<object>();
oneTimeList.AddRange(myList[i]);
Console.WriteLine(oneTimeList);
if (MyList[i].Contains(serchString.ToLower()))
{
Console.WriteLine("Yes you have added this");
}
else if (!myList[i].Contains(serchString))
{
y += 1;
}
}
if (y == myList.Count)
{
Console.WriteLine("You Have not entered this Yet");
}
My logic(maybe not the best in the planet :P) says that i have to make a comparison of all the elements of the array in turn with the search the user made and if its true continue, And in order to make this i need first to get the information of the arrays of the list and convert them to a list and then convert them to lowercase.
Every thing goes fine until the part where i try to add the Arrays to the List and all i am adding are Arrays[].
Any Suggestion on how to approach this issue or how to pass the elements of an ARRAY that is inside of a LIST to a NEW LIST?
It sounds like to want to take an array of strings (assumed as you mention lower casing it), add them all to a list, lower-case them and then compare?
This being the case you don't need to do any of that. You can simply do:
var myArray = new [] { "A", "B", "C" }
var toCheck = "a";
//Use the IEnumerable<T>.Contains() Linq extension
if (myArray.Contains(toCheck, StringComparer.OrdinalIgnoreCase))
{
//...
}
If you really want to add them to a list I can't give you an example using your code, but to "pass elements of an array to a new list" you can do any of the following:
//List<T>(IEnumerable<string>) constructor
var newList = new List<string>(myListOfStrings);
//List<T>.AddRange(IEnumerable<string>)
var newList = new List<string>();
newList.AddRange(myListOfStrings);
//List<T>.Add(T) (adding items one at a time)
var newList = new List<string>();
newList.Add(myListOfStrings[index]);
It's worth noting here as well that any of the above references to myListOfStrings could be an array of strings (string[]) or a list of strings (List<string>) because they both implement IEnumerable<string> which is the type the above methods require (except for Add which wants a single item).
Here is the documentation for List that describes in details how to use each of the above (and all other other available methods...)
I am in bust at the moment, I have this string array:
string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" };
I need to convert them To long array data type in C#:
long[] LongNum= { 4699307989721714673, 4699307989231714673, 4623307989721714673, 4577930798721714673 };
But I have no idea how, is it even possible?
You could use simple Linq extension functions.
long[] LongNum = StringNum.Select(long.Parse).ToArray();
or you can use long.TryParse on each string.
List<long> results = new List<long>();
foreach(string s in StringNum)
{
long val;
if(long.TryParse(s, out val))
{
results.Add(val);
}
}
long[] LongNum = results.ToArray();
var longArray = StringNum.Select(long.Parse).ToArray();
It can probably be done in less code with Linq, but here's the traditional method: loop each string, convert it to a long:
var longs = new List<Long>();
foreach(var s in StringNum) {
longs.Add(Long.Parse(s));
}
return longs.ToArray();
If you are looking for the fastest way with smallest memory usage possible then here it is
string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" };
long[] longNum = new long[StringNum.Length];
for (int i = 0; i < StringNum.Length; i++)
longNum[i] = long.Parse(StringNum[i]);
Using new List<long>() is bad because every time it needs an expansion then it reallocates a lot of memory. It is better to use new List<long>(StringNum.Lenght) to allocate enough memory and prevent multiple memory reallocations. Allocating enough memory to list increases performance but since you need long[] an extra call of ToArray on List<> will do the whole memory reallocation again to produce the array. In other hand you know the size of output and you can initially create an array and do the memory allocation.
You can iterate over the string array and keep converting the strings to numeric using the long.Parse() function. Consider the code below:
string[] StringNum =
{ "4699307989721714673",
"4699307989231714673",
"4623307989721714673",
"4577930798721714673" };
long[] LongNum = new long[4];
for(int i=0; i<4; i++){
LongNum[i] = long.Parse(StringNum[i]);
}
This converts and stores each string as a long value in the LongNum array.
I have a method bringing in text every 600000 milliseconds, this is added to an array through the following method:
String[] namesArray = { };
Array.Resize(ref namesArray, namesArray.Length + 1);
namesArray[namesArray.Length - 1] = nameSplit;
I was curious, is this just replacing the array with the new text, or is it pushing the old index up to 1. Example if the text that came through was Jim, would this be placed in [0]. When the next comes through and it is "Harry", will "Jim" be pushed to 1 and "Harry" to [0]. Let me know if more code is required.
EDIT
Here is what your code is doing:
String[] namesArray = { }; // Create a new zero-element array.
Array.Resize(ref namesArray, namesArray.Length + 1); // Increase size of array by 1.
namesArray[namesArray.Length - 1] = nameSplit; // Assign to array's last element.
Thus, the end-result is that you would have a one-element array whose content is your nameSplit variable. This is equivalent to:
String[] namesArray = { nameSplit };
Subsequent calls will results in a new one-element array being created and assigned to namesArray.
Instead of manually resizing an array, consider using a List<T> instead. It's basically a self-resizing array. Instead of using two arrays, one for the names and another for the amounts, it's better to make a struct or class that groups a name and amount together, so you can use a single list:
public struct NameAndAmount
{
public string Name;
public int Amount;
public NameAndAmount(string name, int amount)
{
Name = name;
Amount = amount;
}
}
List<NameAndAmount> items = new List<NameAndAmount>();
items.Add(new NameAndAmount("test", 100));
However, if you need to perform lookups by name, you may want to use a Dictionary<TKey, TValue> instead, using the names as keys and the amounts as values:
Dictionary<string, int> items = new Dictionary<string, int>();
// Check if a name has been stored before:
if (items.ContainsKey(name))
int previousAmount = items[name];
// Store a name and amount:
items[name] = amount;
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();
I need to copy an array to a linked list OR transform the array in a linked list.
How this can be done in .NET (C# or VB)?
Thanks
Depending on what version we're taking about here, you can :
LinkedList<YourObjectType> ListOfObjects=new LinkedList<YourObjectType>(YourObjectArray);
To go to LinkedList from array:
var array = GetMyArray();
LinkedList<MyType> list = new LinkedList<MyType>(array);
To go to array from LinkedList:
var array = list.ToArray();
In .Net v2.0 or above:
Object[] myArray = new Object[] { 1, "Hello", 2, 3.0 };
LinkedList<Object> linkedList = new LinkedList<Object>(myArray);
You can replace Object with the type of element that the array actually holds.