C# - Linq - Techniques for avoiding repeating same pieces of code I am writing a piece of code for C# Web Api, letting the clients to pass a column name and sort direction as parameter.
Although there are, like, 30-ish properties, so the following code (despite it works) gets ugly after a while.
What are my options to avoid repeating this seemingly same pieces of code?
if (column == nameof(MyModel.ColumnA).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q =&gt; q.ColumnA);
    }

    return queryResult.OrderByDescending(q =&gt; q.ColumnA);
}

if (column == nameof(MyModel.ColumnB).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q =&gt; q.ColumnB);
    }

    return queryResult.OrderByDescending(q =&gt; q.ColumnB);
}

if (column == nameof(MyModel.ColumnC).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
         return queryResult.OrderBy(q =&gt; q.ColumnC);
    }

    return queryResult.OrderByDescending(q =&gt; q.ColumnC);
}

....


```
If you're willing to use the DynamicLinq library, the problem becomes trivial. It allows you to pass a string parameter to the OrderBy method, bypassing your entire logic:
queryResult.OrderBy(column)

If this is related to doing a SQL database lookup, if you think about it, the issue you're facing it a bit of a self-imposed issue, because you start from a string value and you're eventually going to generate a string value (in the SQL query). The issue you're facing is that standard LINQ forces you to map it to an actual property of the entity, which in this case is an unnecessary mapping which DynamicLinq allows you to bypass.
If you want, you could add a bit of validation to confirm that the passed string is a known property of your entity type.
bool columnIsProperty = typeof(MyModel)
                           .GetProperties()
                           .Any(prop =&gt; prop.Name.ToLower() == column.ToLower());

if(columnIsProperty)
    queryResult = queryResult.OrderBy(column);