简体   繁体   中英

Convert array from nullable type to non-nullable of same type?

I would like to convert a Nullable(Of Byte)() array (aka byte?[] ) to a non-nullable array of the same type, that is, from byte?[] to byte[] .

I'm looking for the simpler, easier, faster generic solution, in C# or VB.NET. I've found this generic function to convert between nullable types but I can't find a way to adapt the conversion logic to convert from a nullable type to a non-nullable type.

This is a code example for which I feel the need to perform that kind of conversion:

byte?[] data = {1, 0, 18, 22, 255};
string hex = BitConverter.ToString(data).Replace("-", ", ");

To convert an array of one type to an array of another type, use the Array.ConvertAll method:

byte?[] data = { 1, 0, 18, 22, 255 };
byte[] result = Array.ConvertAll(data, x => x ?? 0);

This is simpler, easier, and faster than using LINQ.

This method has to make an assumption of how to handle a null value. For this solution it is mapped to default(byte) = 0 in order to have input and output to be of the same length.

byte?[] data = {1, 0, 18, 22, 255, null};
var byteArray = data.Select(
                 b => b ?? default(byte)).ToArray();

Found this looking thread for a way myself. I ended up using .OfType(...) to filter on type.

int?[] data = { 1, null, 18, 22, 255 };
var result = data.OfType<int>();
Console.WriteLine(string.Join(",", result)); // 1,18,22,255

This code will return an array of non nullables.

 Dim arr() As Nullable(Of Byte)
 dim nonNullableArray = arr.Select(Function(item) item.Value).ToArray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM