I got the first row of an excel sheet with the following code.
Excel.Range firstRow = ws.UsedRange.Rows[1];
var row = (System.Array) firstRow.Cells.Value;
List<object> Array = row.OfType<object>().ToList();
row
consists of null values.
Eg.
The problem is when it is converted in to list, all the null values are lost. (After this statement)
List<object> Array = row.OfType<object>().ToList();
Eg.
Any ideas how to prevent this from happening ?
From looking at what you are doing
Cast
would be more appropriate thanOfType
.This should do what you want and basically just tell it that all objects should be cast to type object. This will preserve the null.
The reason for the difference is that
OfType
does a check forcurrent is TResult
before returning the cast object and of coursenull is object
will return false and thus it gets dropped. The corollary of this is of course thatCast
can throw exceptions if misused (egCast<int>
on the above sample would throw anInvalidCastException
whereasOfType<int>
would just return the items that could be cast to ints.From: CAST AND OFTYPE