dtretyakov / WindowsAzure

.NET library aimed at managing and querying entities from Windows Azure Storage. It can be used as LINQ to Azure Tables.
MIT License
64 stars 27 forks source link

Add ability to use StartsWith #61

Open xxyuze opened 6 years ago

xxyuze commented 6 years ago
public static class CloudExtensions
    {

        public static async Task<IEnumerable<TElement>> StartsWith<TElement>
        (this CloudTable table, string partitionKey, string searchStr,
        string columnName = "RowKey") where TElement : ITableEntity, new()
        {
            if (string.IsNullOrEmpty(searchStr)) return null;

            char lastChar = searchStr[searchStr.Length - 1];
            char nextLastChar = (char)((int)lastChar + 1);
            string nextSearchStr = searchStr.Substring(0, searchStr.Length - 1) + nextLastChar;
            string prefixCondition = TableQuery.CombineFilters(
                TableQuery.GenerateFilterCondition(columnName, QueryComparisons.GreaterThanOrEqual, searchStr),
                TableOperators.And,
                TableQuery.GenerateFilterCondition(columnName, QueryComparisons.LessThan, nextSearchStr)
                );

            string filterString = TableQuery.CombineFilters(
                TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey),
                TableOperators.And,
                prefixCondition
                );
            var query = new TableQuery<TElement>().Where(filterString);
            return await table.ExecuteQuerySegmentedAsync<TElement>(query,null);
        }
    }