Created
October 19, 2017 15:04
-
-
Save randyburden/20528d561c1dcace08d1b7f3d69ab114 to your computer and use it in GitHub Desktop.
C# method to validate a string-based OrderBy clause to be used in a dynamic LINQ statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
Below is an alternative implementation inspired by the previous version.