cast an Object[] array to an Integer Array - c#

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[];

Related

List box conversion to array 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();

Parse int[] from "1,2,3"

I have a multiselect dropdown called ID that submits ID=1,2,3 which I need parsed into an integer array to do a Contains() on in a filter method. At the moment I use:
string[] ids = Request["ID"].Split(',');
Which I don't really like because its slower to compare string than int. Any suggestions?
Request["ID"].Split(',').Select(x=>int.Parse(x)).ToArray();
Of course, this will throw if any of the resulting numeric strings are not "parseable" (does such a word exist?).
It depends on how many times you will look up in the array if converting to ints are faster or the string comparison is faster.
HashSet<int> ids = new HashSet<int>(from s in Request["ID"].Split(',')
select int.Parse(s));
But probably the fastest if you have many id:s will be to create a HashSet<string>:
HashSet<string> = new HashSet<string>(string[] ids = Request["ID"].Split(','));
int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
First:
string[] arr = Request["ID"].Split(',')
Then:
Array.ConvertAll(arr, s => Int32.Parse(s));
Array.ConvertAll(arr, Int32.Parse);
arr.Select(s => Int32.Parse(s));
arr.Select(Int32.Parse);
Then:
new HashSet<int>(result);
(the most fast container to perform Contains())
See also:
Convert string[] to int[] in one string of code using LINQ
Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()
If you don't have linq, you can:
string[] ids = Request["ID"].Split(',');
int[] items = new int[ids.Length];
for(int i = 0; i<ids.Length; i++)
{
items[i] = int.Parse(ids[i]);
}

converting list<int> to int[]

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);

Dynamic array in C#

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

Convert an array of 'enum' to an array of 'int'

I'm trying to convert an Enum array to an int array:
public enum TestEnum
{
Item1,
Item2
}
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32));
For some reason Convert.ToInt32 doesn't work when used in Array.ConvertAll, so I had to make some changes:
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(ConvertTestEnumToInt));
public static int ConvertTestEnumToInt(TestEnum te)
{
return (int)te;
}
Just out of curiosity, is there any way to have this working without using an extra method?
Regards
Just cast using an anonymous method:
int[] result = Array.ConvertAll<TestEnum, int>(
enumArray, delegate(TestEnum value) {return (int) value;});
or with C# 3.0, a lambda:
int[] result = Array.ConvertAll(enumArray, value => (int) value);
Luckily for us, C# 3.0 includes a Cast operation:
int[] result = enumArray.Cast<int>().ToArray();
If you stop using arrays and start using IEnumerable<>, you can even get rid of the ToArray() call.
enumArray.Select(x => (int) x)).ToArray()
This worked like a charm:
var intArray = enumArray.Select(e => (int)e).ToArray();
as did this:
var intList = enumArray.Select(e => (int)e).ToList();
FYI: tested on .Net4ClientProfile and VS2010
Actually, you don't even need to use LINQ. You can just cast it in a normal way, provided that you drop the type down to object.
Having:
enum One { one0, one1, one2, one3 };
enum Two { two0, two1, two2, two3 };
One[] vals = new One[] { One.one0, One.one3 };
we can play:
//Two[] aa = (Two[])vals; // impossible
Two[] aa = (Two[])(object)vals; // possible!
Two bb = aa[1]; // == Two.two3
At first, I was really suprised that the second line doesn't throw InvalidCast. But it does not.
Looking at the types explains things a little:
bool check2 = bb.GetType().FullName == "Two"; // well, you'd guess that
bool check3 = aa.GetType().FullName == "One[]"; // what?!
Seriously! The aa array is not Two[]. The array type has been "lost by variable" when it was cast to object, but both vals and (object)vals of course still refer to the same object. Then, after the following cast, it's still the aa object, the original array of One[], just hidden behind a new variable type.
The bb object/variable has type of Two because the array's item read as an item of a Two[] array (along with the variable's types). The real array One[] is concealed by the Two[] type, so indexing the Two[] must result in value of Two type.
Furthermore, since the actual type is hidden and since Enum types seem to be treated lightly, let's check another thing:
var numbers = (int[])(object)vals;
var cc = numbers[0] + 10; // == 10, from one0's value
var dd = numbers[1] + 10; // == 13, from one3's value
and similarly:
bool check4 = numbers.GetType().FullName == "One[]"; // not System.Int32[]
So, as you might already guess, the other way around is possible too:
var numbers2 = new int[]{ 0, 2, 99 };
var enums = (One[])(object)numbers2;
One ee = enums[0]; // == One.one0
One ff = enums[1]; // == One.one2
One gg = enums[2]; // == ((One)99)
and int[] also remembers its real type, even if casted to One[]:
bool check5 = numbers2.GetType().FullName == "System.Int32[]";
Even further, you cannot trust the as and is operators when the array is passed as object:
bool really_true1 = vals is One[];
bool really_true2 = vals is Two[];
bool really_true3 = vals is System.LoaderOptimization[];
This one was a 'gotha!' for me recently.
It actually reuses the original array object (instead of duplicating it like with LINQ) and it exposes it as different type - be it Two[] or int[]. It's seems to be a "true cast", no boxing. Much different than LINQ-driven copying&conversion.
int[] b = Array.ConvertAll((int[])Enum.GetValues(typeof(TestEnum)), Convert.ToInt32);

Categories

Resources