advertise with us

LINQ Query to Filter Data with Null Values in C#

Filtering data with null values is a common requirement when working with collections in C#. Whether you’re processing data from databases, APIs, or files, handling null values effectively ensures reliable and error-free operations. LINQ (Language Integrated Query) provides an elegant way to filter data and manage null values in C#.


Why Filter Null Values?

Null values in data can cause:

  1. Runtime Errors: Accessing null values without checks can result in NullReferenceException.
  2. Incorrect Results: Unhandled nulls can lead to inaccurate computations or data processing.
  3. Data Cleaning: Filtering null values improves the quality and usability of your data.

Example Dataset

Consider the following list of objects:

public class Product
{
public int? Id { get; set; }
public string Name { get; set; }
public decimal? Price { get; set; }
}

List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1000m },
new Product { Id = 2, Name = null, Price = 500m },
new Product { Id = null, Name = "Tablet", Price = null },
new Product { Id = 4, Name = "Monitor", Price = 300m }
};

Scenarios and LINQ Queries

1. Filter Out Objects with Any Null Value

To exclude products where any property is null:

var validProducts = products
.Where(p => p.Id != null && p.Name != null && p.Price != null)
.ToList();

Console.WriteLine("Products with no null values:");
foreach (var product in validProducts)
{
Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
}

Output:

Products with no null values:
Id: 1, Name: Laptop, Price: 1000

2. Filter Objects with a Specific Null Property

To include only products where the Name property is null:

var unnamedProducts = products
.Where(p => p.Name == null)
.ToList();

Console.WriteLine("Products with null names:");
foreach (var product in unnamedProducts)
{
Console.WriteLine($"Id: {product.Id}, Price: {product.Price}");
}

Output:

Products with null names:
Id: 2, Price: 500

3. Include Only Objects with Non-Null Values for a Specific Property

To include products where the Price is not null:

var pricedProducts = products
.Where(p => p.Price != null)
.ToList();

Console.WriteLine("Products with non-null prices:");
foreach (var product in pricedProducts)
{
Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
}

Output:

Products with non-null prices:
Id: 1, Name: Laptop, Price: 1000
Id: 2, Name: null, Price: 500
Id: 4, Name: Monitor, Price: 300

4. Replace Null Values with Default Values

To handle null values by replacing them with defaults:

var productsWithDefaults = products
.Select(p => new
{
Id = p.Id ?? 0,
Name = p.Name ?? "Unknown",
Price = p.Price ?? 0m
})
.ToList();

Console.WriteLine("Products with default values:");
foreach (var product in productsWithDefaults)
{
Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
}

Output:

Products with default values:
Id: 1, Name: Laptop, Price: 1000
Id: 2, Name: Unknown, Price: 500
Id: 0, Name: Tablet, Price: 0
Id: 4, Name: Monitor, Price: 300

5. Combine Filtering and Transformation

You can filter out products with null Name and transform the results into a simpler structure:

var filteredProducts = products
.Where(p => p.Name != null)
.Select(p => new
{
ProductName = p.Name,
Price = p.Price ?? 0m
})
.ToList();

Console.WriteLine("Filtered and transformed products:");
foreach (var product in filteredProducts)
{
Console.WriteLine($"Name: {product.ProductName}, Price: {product.Price}");
}

Output:

Filtered and transformed products:
Name: Laptop, Price: 1000
Name: Monitor, Price: 300

Key LINQ Techniques

ScenarioLINQ Query
Exclude objects with any null valueWhere(p => p.Id != null && p.Name != null && p.Price != null)
Include objects with specific null valueWhere(p => p.Name == null)
Include objects with specific non-null valueWhere(p => p.Price != null)
Replace null values with defaultsSelect(p => new { Id = p.Id ?? 0, Name = p.Name ?? "Default", Price = p.Price ?? 0m })
Filter and transform dataWhere(p => p.Name != null).Select(p => new { ProductName = p.Name, Price = p.Price ?? 0m })

Conclusion

Filtering data with null values in C# using LINQ is both powerful and concise. Whether you want to exclude items with null properties, include only non-null data, or replace nulls with default values, LINQ provides a clean syntax to handle these scenarios. By mastering these techniques, you can efficiently work with collections while ensuring robust data processing in your C# applications.


Need Help with Your C# Projects?

We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.

CONTACT US NOW