简体   繁体   中英

Convert IEnumerable<T?> to IEnumerable<T>

I'm looking to be able to take a list of nullable types T?, and remove any null values, leaving a type of T. For instance:

        List<int?> xs = new List<int?>() {1, 2, 3};
        
        // this method works
        IEnumerable<int> xs2 = xs.Select(x => x ?? 0);
        
        // this method does not
        IEnumerable<int> xs3 = xs.Where(x => x != null);

I appreciate C# isn't able to infer the type of the list such that it would be able to tell that there are no nulls in the list. But I'm struggling to find the best way to do this without just doing an explicit cast as in:

IEnumerable<int> xs3 = xs.Where(x => x != null).Select(x => (int)x);

The problem I have with this is that, if the Where statement wasn't there, then the code would still pass the type check, but would have a runtime error. Is there a way to do this in C# such that, at compile time, I can guarantee the type of the list is not nullable, and that it contains no nulls?

dotnetfiddle

I'd ideally like to do this in a generic way (but I have a separate problem there).

I managed to find this question which provides a good way of converting the values by converting nulls to a value of the type.

Is there a way to do this?

You can use .Value :

IEnumerable<int> xs3 = xs.Where(x => x != null).Select(x => x.Value);

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