OliverRadini
OliverRadini

Reputation: 6467

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?

Upvotes: 1

Views: 1238

Answers (1)

Peter B
Peter B

Reputation: 24147

You can use .Value:

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

Upvotes: 2

Related Questions