Is there builtin method that would do this or do I always have to manually create a new array and then fill it up with a foreach loop
list.ToArray()
List<int> list = ...
...
int[] array = list.ToArray();
You can also use the CopyTo method :
int[] array = new int[list.Count];
list.CopyTo(array);
Related
I have a list
List<int> list = new List<int>();
Now I want to add this to a Jagged Array
int[][] A = new int[][] { list.ToArray() };
This code on top is ok, but the problem is that all values in the list are add in the first block!
Well, then, this will be solved:
int[] x1 = list.ToArray();
int[][] A = new int[][] { new[] { x1[0] }, new[] { x1[1] }, new[] { x1[2] }, new[] { x1[3] } };
But (the code above) I've done this manually now, that's just the first four indexes I've of list put in the array..
How can I add entire list (all indexes) to my jagged array (with circles or other methods).
Use a projection.
This will iterate through the list, creating a new array with the sole value of the current iteration, and then end by creating an array of all of those arrays.
int[][] A = list.Select(i => new[] { i }).ToArray();
As an aside, and as [#maccettura] notes, this is a jagged array (where each member of the array is also an array itself).
It's hard for me to explain, so let me show it with pseudo code:
ObjectX
{
int a;
string b;
}
List<ObjectX> list = //some list of objectsX//
int [] array = list.Select(obj=>obj.a);
I want to fill an array of ints with ints from objectsX, using only one line of linq.
You were almost there:
int[] array = list.Select(obj=>obj.a).ToArray();
you need to just add ToArray at the end
The only problem in your code is that Select returns IEnumerable.
Convert it to an array:
int[] array = list.Select(obj=>obj.a).ToArray();
What is the easiest way to cast an object array to an integer array?
ArrayList al = new ArrayList();
object arrayObject = al.ToArray();
int[]arrayInteger = ?
Thanks
If you import System.Linq namespace you can do this:
int[] arrayInteger = a1.Cast<int>().ToArray();
Use int[]arrayInteger = (int[])al.ToArray(typeof(int));
But unless you are using .Net 1.1, user a List<int> instead.
(object[] eventTypes) Assuming eventTypes are all objects with integer values, this would do it:
int[] eventTypeIDs = eventTypes.Select( Convert.ToInt32).ToArray();
You could use Array.ConvertAll
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => (int)o);
One thing to consider is since this is an object array all the values may not be int
This is the handy thing about ConvertAll as you can add simple conversion logic to catch errors.
Scenario:
ArrayList al = new ArrayList() { 1,"hello",3,4,5,6 };
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => { int val = -1; return int.TryParse(o.ToString(), out val) ? val : -1;});
This way we can perform a TryParse on the object to avoid any InvalidCastException due to bad data.
or
int[] intArray = object as int[];
I'm trying to convert a listbox to an array:
var modarray = listBox1.Items.Cast<String>().ToArray();
but then I also need to use an int array so I tried the following:
int[] arr = modarray.Cast<int>().ToArray();
I get an error that suggests that is not possible to convert the array. Can anybody help me please?
Try this:
int[] arr = modarray.Select(int.Parse).ToArray();
This will use the int.Parse() method for each of the strings in the original array to create a new integer array.
Try this instead :
int[] arr = modarray.Select(I => Convert.ToInt32(I)).ToArray();
.Cast<int>() is like foreach (var i in list) yield return (int)i;
Which if your items are strings underneath will fail.
I believe you need: int[] arr = modarray.Select(s => Int32.Parse(s)).ToArray();
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