简体   繁体   中英

Check if list is null before using linq

Using LINQ I want to check if myList.= null and then perform a Where.

I know I can write

if (myList.= null { myList.Where(p => px == 2 && p;y == 3); }

But I want to use: myList?.Where(p => px == 2 && py == 3);

Does this work?

If not, what are other elegant solutions you know?

Yes, list?.Where(i => i > 1) is a legit expression, which called "null propagation operator".

On of the problem of using null propagation operator is that you will start writing code like this

var result = list?.Where(i => i > 1)?.Select(i => i * 2)?.Where(i => i % 2 == 0)?.ToList();
// result can be null and still requires check for null

.. what are other elegant solutions you know?

Other elegant solution would be to make sure that whenever function returns a collection it never return null but an empty collection.

Such convention will make your code easier to read and understand actual intentions of the code, make it easy to test (less test cases to test), less "noisy null checks".

Notice that LINQ extension methods never return null .

If you are using libraries which returns null for a collection but you don't have access to the code - "convert" null to an empty collection and continue using as valid collection.

var checkedList = givenList ?? Enumerable.Empty<int>();
checkedList.Where(i => i > 1).ToList();

If you find yourself doing this a lot, create an extension method.

public IEnumerable<T> EmptyIfNull(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();     
}

Usage

var result = givenList.EmptyIfNull().Where(i => i > 1).ToList();

If you build using C# 6 / Visual Studio 2013 or later, you are allowed to write:

var result = myList?.Where(p => p.x == 2 && p.y == 3);

So if myList is null , Where is not evaluated and result will be null , else of type of the resulting query ( IEnumerable<T> or IQueryable<T> ).

Null-conditional operators

Also you can write:

var result = myList?.Where(p => p.x == 2 && p.y == 3) ?? someValue;

So if myList is null , result will be assigned by someValue .

Null-coalescing operator

You can check option in Project Settings > Build > Advanced options > Language version .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM