Generate filter criteria based on multiple field combinations The PrepareConditions method in the FeeTypeQueryService class prepares the conditions based on the searchConditions parameter and returns as an object. searchConditions can only have 3 combinations, such as:


Filter by TenantId, FeeTypeId
Filter by TenantId, FeeTypeName
Filter by TenantId, FeeTypeId, FeeTypeName


Note: The TenantId is mandatory for all the filter criterias.

Question: Is there a better way to write the PrepareConditions method so that it doesn't become complicated with a long list of conditional statements? When I start to have more properties in the FeeTypeSearchModel class, this may get dirty - I think.

Sample code:

FeeTypeQueryService.cs

public sealed class FeeTypeQueryService
{
    private object PrepareConditions(FeeTypeSearchModel searchConditions)
    {
        object conditions = null;

        if (searchConditions.FeeTypeId.HasValue &amp;&amp; string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value };
            return conditions;
        }

        if (!searchConditions.FeeTypeId.HasValue &amp;&amp; !string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, searchConditions.FeeTypeName };
            return conditions;
        }

        if (searchConditions.FeeTypeId.HasValue &amp;&amp; !string.IsNullOrEmpty(searchConditions.FeeTypeName))
        {
            conditions = new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value, searchConditions.FeeTypeName };
            return conditions;
        }

        conditions = new { TenantId };
        return conditions;
    }
}


FeeTypeSearchModel.cs

public sealed class FeeTypeSearchModel
{
    public int? FeeTypeId { get; set; }
    public string FeeTypeName { get; set; }
}
Usually I tell at code reviews that saving a level of indentation is a good thing, but in the case of your code I wondered why you placed three times the same condition because I had a hard time to notice the !'s so I would suggest to take a different route, otherwise you will be confused in half a year as well.  

I would use a `if..else if´ like so  

if (searchConditions.FeeTypeId.HasValue)
{
    if (string.IsNullOrEmpty(searchConditions.FeeTypeName))
    {
        return new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value };
    }
    return new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value, searchConditions.FeeTypeName };
}
else if(string.IsNullOrEmpty(searchConditions.FeeTypeName))
{
    return new { TenantId };    
}

return new { TenantId, searchConditions.FeeTypeName };