Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

I have a simple LinQ query in this way:

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

However, Property could be null and then I get an error. So I would like to know if there is any way to check if it is null, if not null, do the comparation, if it is null, throw an exception.

Because if not, I have to use a foreach to check each element, in this way:

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);
    }
}

Thanks.

like image 445
Álvaro García Avatar asked Dec 07 '22 21:12

Álvaro García


1 Answers

Yes you can extend the lambda just like that:

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

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

like image 80
René Vogt Avatar answered Dec 11 '22 06:12

René Vogt