See this sample:
var list = new List<string?>();
foreach (string item in list.Where(i => i != null))
{
if (item.Length == 2)
{
...
}
}
In this sample, I get possible null reference in two places. The foreach variable and the dereferencing of Length in if. The second one I can easily fix by adding a dammit (null-forgiving) operator like this: item!.Length
Is there any way to do the same thing to the first one? I know that I can mark it as nullable string and check again but, I have already checked.
When you apply filtering using Where, you eliminate all null values, but this doesn't change the type of values.
All you need is to cast the results after filtering to the proper type:
foreach (string item in list.Where(i => i != null).Select(x => x!))
Unfortunately the Where predicate doesn't modify the caller's view of whether items in the enumerable are null or not.
The approach given by Dmitry involves additional runtime overhead due to the use of an extra Select call.
You can avoid that overhead via this extension method:
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
{
foreach (T? item in source)
{
if (item != null)
yield return item;
}
}
Your code then becomes:
foreach (string item in list.WhereNotNull())
{
if (item.Length == 2)
{
...
}
}