Is it possible to use conditional expression inside where clause in LinQ?

I have a simple LinQ query like this:

myList.Where(x=> x.Property.Property2 == 5);

However, the property may be null, and then I get an error. So I would like to know if there is a way to check if it is null, if not null, then compare if it is null, throws an exception.

Because, if not, I have to use foreach to check each element as follows:

List<MyType> myLstResult = new List<MyType>();
foreach(MyType iterator in myList)
{
    if(iterator.Property == null)
    {
        throw new ArgumentNullException();
    }
    if(iterator.Property.Property2 == 5)
    {
        myLstresult.Add(iterator);
    }
}

Thank.

+4
source share
2 answers

Yes, you can expand the lambda like this:

myList.Where(x=> 
    {
        if (x.Property == null)
            throw new ArgumentNullException();
        return x.Property.Property2 == 5;
    });

This, of course, will only work in "normal" linq. Linq-to-sql or -entity query providers will probably not be able to translate this to sql.

+7

.

null # 6:

myList.Where(x=> x.Property?.Property2 == 5);

:

 myList.Where(x=> x.Property != null && x.Property.Property2 == 5);

, , , . , LINQ :

https://msdn.microsoft.com/en-us/library/bb513730.aspx

- , ,

, foreach, ( ), try-catch:

List<MyType> myLstResult = null;
try
{
    myLstResult = myList.Where(x=> x.Property.Property2 == 5).ToList();
}
catch(NullReferenceException nullref)
{
    throw new ArgumentNullException("MyType.Property must not be null", nullref);
}
// ...

, . LINQ, Linq-To-Sql Linq-To-Entities, .

: , ThrowIfArgumentNull, :

public static IEnumerable<TSource> ThrowIfArgumentNull<TSource, TNullable>(this IEnumerable<TSource> enumeration, Func<TSource, TNullable> mightBeNullSelector, string argumentName) 
    where TNullable : class
{
    foreach (TSource item in enumeration)
    {
        if (mightBeNullSelector(item) == null)
            throw new ArgumentNullException(argumentName);
        yield return item;
    }
}

:

List<MyType> myLstresult = myList
    .ThrowIfArgumentNull(x => x.Property, "MyType.Property")
    .Where(x => x.Property.Property2 == 5)
    .ToList();
+7

All Articles