简体   繁体   中英

How to preserve null in system.array - C#?

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 than OfType .

List<object> Array = myvalues.Cast<object>().ToList();

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 for current is TResult before returning the cast object and of course null is object will return false and thus it gets dropped. The corollary of this is of course that Cast can throw exceptions if misused (eg Cast<int> on the above sample would throw an InvalidCastException whereas OfType<int> would just return the items that could be cast to ints.

From: CAST AND OFTYPE

There's one important case to consider where Cast will successfully return a value and OfType will ignore it: null references (with a nullable return type). In normal code, you can cast a null reference to any nullable type (whether that's a reference type or a nullable value type). However, if you use the "is" C# operator with a null value, it will always return false. Cast and OfType follow the same rules, basically.

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