Is there a way to prevent an item being stored in collection if condition fails. In this example I store null but it still counts as a collection item and can be enumerated. In collection I want to have only values from failed checks and no null values.
if (part.IsFailure || customer.IsFailure || provider.IsFailure)
{
return BadRequest(new InvalidArgumentDetails(new List<InvalidArgumentFieldDetail>()
{
part.IsFailure ? new InvalidArgumentFieldDetail(nameof(part.Id), part1.Error.ErrorCode.ToString(), part.Error.Message, null) : null,
customer.IsFailure ? new InvalidArgumentFieldDetail(nameof(customer.Id), customer.Error.ErrorCode.ToString(), customer.Error.Message, null) : null,
provider.IsFailure ? new InvalidArgumentFieldDetail(nameof(provider.Id), provider.Error.ErrorCode.ToString(), provider.Error.Message, null) : null,
}));
}
>Solution :
Don’t try to put everything on one line of code. You can conditionally add elements to the list by using if statements. For example:
var result = new List<InvalidArgumentFieldDetail>();
if (part.IsFailure)
result.Add(new InvalidArgumentFieldDetail(nameof(part.Id), part1.Error.ErrorCode.ToString(), part.Error.Message, null));
if (customer.IsFailure)
result.Add(new InvalidArgumentFieldDetail(nameof(customer.Id), customer.Error.ErrorCode.ToString(), customer.Error.Message, null));
if (provider.IsFailure)
result.Add(new InvalidArgumentFieldDetail(nameof(provider.Id), provider.Error.ErrorCode.ToString(), provider.Error.Message, null));
if (result.Any())
return BadRequest(new InvalidArgumentDetails(result));
Alternatively, if you want to build the list with null elements (which your quick edit and your recent comment imply) then you can simply filter those elements out afterward:
if (part.IsFailure || customer.IsFailure || provider.IsFailure)
{
return BadRequest(new InvalidArgumentDetails(new List<InvalidArgumentFieldDetail>()
{
// your existing conditions to add three elements
}.Where(x => x != null)));
} // ^--- filter out null elements here
Any way you look at it, you only have two options:
- Don’t add
nullelements to the list. - Add
nullelements to the list and then remove them.