C# Cast Entire Array?
The proposed LINQ solution using Cast
/'Select' is fine, but since you know you are working with an array here, using ConvertAll
is rather more efficienct, and just as simple.
var newArray = Array.ConvertAll(array, item => (NewType)item);
Using ConvertAll
means
a) the array is only iterated over once,
b) the operation is more optimised for arrays (does not use IEnumerator<T>
).
Don't let the Converter<TInput, TOutput>
type confuse you - it is just a simple delegate, and thus you can pass a lambda expression for it, as shown above.
C# cast array to element type
This is not a good idea. You have no way to constrain TResult
to an array, so with your current code, someone could call Excute<int>
and get a runtime exception, yuck!
But, why constrain to an array to begin with? Just let the generic parameter be the type of the element itself:
public TResult[] Execute<TResult>()
{
var myArray = ...
return myArray.Cast<TResult>().ToArray();
}
UPDATE: In response to your comments:
If Execute
is an interface method you can not change, then you can do the following:
public static TResult Execute<TResult>()
{
var myArray = new List<object>() { ... };
var entityType = typeof(TResult).GetElementType();
var outputArray = Array.CreateInstance(entityType, myArray.Count);
Array.Copy(myArray.ToArray(), outputArray, myArray.Count); //note, this will only work with reference conversions. If user defined cast operators are involved, this method will fail.
return (TResult)(object)outputArray;
}
How do I cast/convert an array of objects to generic type T when T is defined as an array?
You are not really using the features of generics here, except getting the type via typeof(T). So a solution without generics would be:
public class Foo
{
public object Convert(string value, Type t)
{
if (t.IsArray)
{
string[] values = value.Split(',');
Type elementType = t.GetElementType();
var array = Array.CreateInstance(elementType, values.Length);
for (var i = 0; i < values.Length; i++)
{
array.SetValue(elementType.IsEnum ? Enum.Parse(elementType, values[i], true) : ChangeType(values[i], elementType), i);
}
return array;
}
else
{
return ChangeType(value, t);
}
}
private object ChangeType(string value, Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default;
}
type = Nullable.GetUnderlyingType(type);
}
return System.Convert.ChangeType(value, type);
}
}
Note that I use Array.CreateInstance
to create e.g. a proper int[]
instead of the object[]
created by your values.Select(v => elementType.IsEnum ? Enum.Parse(elementType, v, true) : ChangeType(v, elementType)).ToArray()
.
If you want, you can still have a generic version on top of it:
public class Foo<T> : Foo
{
public T Convert(string value)
{
return (T)Convert(value, typeof(T));
}
}
Convert an array of object to a list of a class
You can use LINQ's Cast
and OfType
methods, depending on what you want to happen if your array contains an element that is not of type MyClass
.
If you want to throw an exception upon encountering an invalid element, use:
var myList = myArray.Cast<MyClass>().ToList();
If you want to silently ignore all items that are not MyClass
, use:
var myList = myArray.OfType<MyClass>().ToList();
Casting entire array of objects to string
Probably not the most efficient way to do it...it has the benefit of working when the objects aren't necessarily strings.
string[] output = (from o in objectArray
select o.ToString()).ToArray()
Down casting an array of Int[] into an array of Byte[]
You might think this would work:
byte[] myByteArray = myIntArray.Cast<byte>().ToArray();
But it doesnt - see Why Enumerable.Cast raises an InvalidCastException?
You can use Select
though to project to a new array.
byte[] myByteArray = myIntArray.Select(i => (byte)i).ToArray();
Live demo: https://rextester.com/KVR50332
Convert Array to custom object list c#
You will need to use the Select operator and assign your array of strings to your Portfolio object. Something like this:
myArray.Select(array => new Portfolio { Field1 = array[0], Field2 = array[1] }).ToList()
In C# cast array without making a copy
I do not care about endianness. I want memory representation of shorts written to a file in whatever the machine representation of short is.
This is the first impossible thing - endianness changes the memory representation, so reading from successive byte addresses starting at the address of the first short in the array will result in different byte patterns depending on the machine endianness.
The second impossible thing is that arrays in the CLR have type and length information encoded with the data. You cannot change this header information, or else you would break the garbage collector. So given a short[]
array, you cannot convert it to a byte[]
array. You might get to a byte
pointer using C++ clr or unsafe code, but you still won't get to a CLR array.
If you really cannot control the code which takes the byte array, you might be able to change the code manipulating the shorts. Using a MemoryStream
over the byte array would allow you to read and write data to it, you could wrap the array as an IList<short>
, or you could just create accessor extension functions to get the data as shorts.
public sealed class ShortList :IList<short>
{
private readonly byte[] _array;
public short this[int index]
{
get { return (short)_array[index/2]<<8 | _array[index/2+1] ; }
}
public int Count
{
get { return _array.Length/2; }
}
... many more methods in IList
Casting of int array into double array in immediate window?
That cast is illegal. Just try to compile it and you will see that it doesn't work either.
The following code will perform this conversion:
var d = i.Select(x => (double)x).ToArray();
Unfortunately, you can't use it in the immediate window because it doesn't support lambda expressions.
A solution that doesn't require lambda expressions is the following:
i.Select(Convert.ToDouble).ToArray();
This could work because there is no lambda expression. Thanks to Chris for the idea.
Related Topics
Setting Dropdownlist Selecteditem Programmatically
C# ASP.NET Write File to Client
Why Does Binarywriter Prepend Gibberish to the Start of a Stream? How to Avoid It
Ef 6 - How to Correctly Perform Parallel Queries
Is There Any Performance Difference Between ++I and I++ in C#
Passing Command Line Parameters with Visual Studio C#
Is This a Bad Practice to Catch a Non-Specific Exception Such as System.Exception? Why
Task.Factory.Startnew with Async Lambda and Task.Waitall
Project Builds But Can't Publish
The Entity or Complex Type ' ' Cannot Be Constructed in a Linq to Entities Query
Validate JSON Against JSON Schema C#
Regex: Repeated Capturing Groups
How to Use Class Name as Parameter in C#
Thread Safety of a Dictionary<Tkey, Tvalue>
Does Filestreamresult Close Stream
How to Change Listview Selected Row Backcolor Even When Focus on Another Control