Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# method to validate a string-based OrderBy clause to be used in a dynamic LINQ statement
internal void ValidateOrderByClause(string orderBy, string[] supportedOrderByFields)
{
if (!string.IsNullOrWhiteSpace(orderBy))
{
var orderBys = orderBy.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (var orderByClause in orderBys)
{
var orderByClauseParts = orderByClause.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
var orderByClauseField = orderByClauseParts[0];
if (!supportedOrderByFields.Contains(orderByClauseField, StringComparer.OrdinalIgnoreCase))
{
throw new Exception($"'{orderByClauseField}' is not a supported ORDER BY field. Supported fields: {string.Join(",", supportedOrderByFields)}");
}
if (orderByClauseParts.Length > 1)
{
var orderByClauseSortOrder = orderByClauseParts[1];
var supportedOrderBySortOrders = new[] { "ASC", "ASCENDING", "DESC", "DESCENDING" };
if (!supportedOrderBySortOrders.Contains(orderByClauseSortOrder, StringComparer.OrdinalIgnoreCase))
{
throw new Exception($"'{orderByClauseSortOrder}' is not a supported ORDER BY sort order. Supported sort orders: {string.Join(",", supportedOrderBySortOrders)}");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment