C# 在linq查询中处理空数组
我有一个linq查询,其中包含一个值数组。我遇到的问题是,如果数组为空/null,它将中断我的查询。如何在linq查询中处理这个问题。我的另一个选择是在执行linq查询之前检查数组的长度,但我想知道是否可以在查询中包含此检查 代码 试试这个:C# 在linq查询中处理空数组,c#,linq,C#,Linq,我有一个linq查询,其中包含一个值数组。我遇到的问题是,如果数组为空/null,它将中断我的查询。如何在linq查询中处理这个问题。我的另一个选择是在执行linq查询之前检查数组的长度,但我想知道是否可以在查询中包含此检查 代码 试试这个: var entities = await _DbContext.MasterProductView .Where(e => query.SubCategory.Any() ? e.Bus
var entities = await _DbContext.MasterProductView
.Where(e => query.SubCategory.Any() ? e.BusinessUnit == query.BusinessUnit &&
e.Category == query.Category &&
query.SubCategory.Contains(e.SubCategory) : e.BusinessUnit == query.BusinessUnit &&
e.Category == query.Category)
.Select(e => new OptionDto() { Value = e.Brand, Label = e.Brand })
.Distinct()
.OrderBy(e => e.Label)
.ToListAsync(cancellationToken);
空数组可能没有问题,只有空数组。您可以将与结合使用
var entities = await _DbContext.MasterProductView
.Where(e => query.SubCategory.Any() ? e.BusinessUnit == query.BusinessUnit &&
e.Category == query.Category &&
query.SubCategory.Contains(e.SubCategory) : e.BusinessUnit == query.BusinessUnit &&
e.Category == query.Category)
.Select(e => new OptionDto() { Value = e.Brand, Label = e.Brand })
.Distinct()
.OrderBy(e => e.Label)
.ToListAsync(cancellationToken);
// Properties
public string BusinessUnit { get; set; }
public string Category { get; set; }
public string[] SubCategory { get; set; }
var entities = await _DbContext.MasterProductView
.Where(e => e.BusinessUnit == query.BusinessUnit &&
e.Category == query.Category &&
query.SubCategory?.Contains(e.SubCategory) ?? false)
.Select(e => new OptionDto() { Value = e.Brand, Label = e.Brand })
.Distinct()
.OrderBy(e => e.Label)
.ToListAsync(cancellationToken);