Convert List<DTO?> to List<DTO>

Viewed 258

I want convert List<DTO?> to List

List<DTO?> items = new List<DTO?>();

List<DTO> notNullItems = items.Where(c=>c!=null).ToList();

But it does not work!

Doesn't match target type

2 Answers

You can try to use Select the Value property because the type might not be matched when you only use Where the type still be DTO? nullable type.

List<DTO> notNullItems = items.Where(c=>c!=null)
                              .Select(x => x.Value).ToList();

As @Jeroen Mostert commented if your type isn't nullable Cast might be more suitable.

List<DTO> notNullItems = items.Where(c=>c!=null)
                              .Cast<DTO>.ToList();

Alternative you can use the null-forgiving operator (!).

If you add ! after the .ToList(), you'll the C# compiler that you know it's not null:

List<DTO> notNullItems = items.Where(c => c != null).ToList()!;

This will have better performance than .Cast<DTO>() since it doesn't call a method. But we're probably talking nanoseconds here.

Note that this only works with classes. If you're using Nullable<T>, then you'll have to use .Select(c => c.Value).

Related