Successfully added
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
- We use LINQ extension methods
Whereto filter out null values andSelectto convert nullable strings to non-nullable strings (string!indicates a non-nullable reference type in C# 8.0 and later). - Finally, we use
ToList()to convert the filtered enumerable to aList<string>.
Referenced in:
Comments