C# by Shawn

Removing Null Values from a List in C#

To filter out nullable strings and obtain only non-null strings, you can use LINQ Where method along with a null check. Here's an example:

IEnumerable<string?> nullableStrings //

List<string> nonNullStringsList = nullableStrings
    .Where(s => s != null) // Filter out null values
    .Select(s => s!)       // Convert nullable strings to non-nullable
    .ToList();             // Convert IEnumerable to List
  1. We use LINQ extension methods Where to filter out null values and Select to convert nullable strings to non-nullable strings (string! indicates a non-nullable reference type in C# 8.0 and later).
  2. Finally, we use ToList() to convert the filtered enumerable to a List<string>.

Comments