📜  linq select if different null (1)

📅  最后修改于: 2023-12-03 15:02:41.426000             🧑  作者: Mango

LINQ Select If Different Null

LINQ is a great tool for querying data in C#. However, sometimes we want to filter or transform the data based on a condition. One common scenario is when we have nullable data and we only want to perform some operation if the value is not null. In this case, we can use the LINQ Select method with a lambda expression that checks for null values.

Syntax

The basic syntax for using Select with a null check is as follows:

var result = collection.Select(x => x != null ? SomeOperation(x) : defaultValue);

Here, collection is the collection of nullable values, SomeOperation is the operation we want to perform on non-null values, and defaultValue is the value to use when the value is null. The lambda expression checks whether the value is null and performs the appropriate operation.

Example

Let's say we have a List<int?> that contains some nullable integers. We want to convert the values to their ToString representation, but replace null values with the string "N/A". We can use Select with a null check like this:

var numbers = new List<int?> { 1, null, 3, null, 5 };
var result = numbers.Select(x => x != null ? x.ToString() : "N/A");

The result variable will contain the sequence "1", "N/A", "3", "N/A", "5".

Conclusion

Using the LINQ Select method with a null check is a simple and effective way to filter or transform a collection of nullable values. By using a lambda expression that checks for null values, we can perform different operations depending on whether the value is null or not.