Type narrowing for LINQ function Where #9167
-
I find myself writing a lot of code following this pattern: List<string?> someList = ["foo,bar,baz", null, "foo"];
var res = someList
.Where(r => r!=null)
.SelectMany(r => r!.Split(',')); Without LINQ I don't have to do List<string?> someList = ["asda", null, ""];
List<string> res = [];
foreach (var r in someList) {
if (r!=null) {
res.AddRange(r.Split(','));
}
} This is not only something I encounter with nullability, here is another example: List<ISomeInterface> someList = [/* Imagine there being something here */];
var res = someList
.Where(r => r is SomeImplClass)
.Select(r => (r as SomeImplClass)!.Foo()); Would be nice if the following code worked: List<ISomeInterface> someList = [/* Imagine there being something here */];
var res = someList
.Where(r => r is SomeImplClass)
.Select(r => r.Foo()); I can see how this might not be wanted, maybe |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
You can use the List<ISomeInterface> someList = [/* Imagine there being something here */];
var res = someList
.OfType<SomeImplClass>()
.Select(r => r.Foo()); |
Beta Was this translation helpful? Give feedback.
-
public static partial class _IEnumerable_Extensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> This)
where T : class
=> This.Where(x=>x != null)!;
} |
Beta Was this translation helpful? Give feedback.
You can use the
.OfType<T>()
method.