问题
I would like to convert a Nullable(Of Byte)()
array (a.k.a. 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("-", ", ");
回答1:
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.
回答2:
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();
回答3:
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
回答4:
This code will return an array of non nullables.
Dim arr() As Nullable(Of Byte)
dim nonNullableArray = arr.Select(Function(item) item.Value).ToArray()
来源:https://stackoverflow.com/questions/39310404/convert-array-from-nullable-type-to-non-nullable-of-same-type