1

如何为 myQuery 分配初始值,其中我使用 AND 和 foreach 循环附加条件。

我正在尝试执行以下操作:

string myQuery = string.empty;

foreach (string myCondition in myConditionLists)
{
    myQuery = TableQuery.CombineFilters(
        myQuery,
    TableOperators.And,
    TableQuery.GenerateFilterCondition(nameof(MyClass.MyProperty), 
        QueryComparisons.NotEqual, myCondition));
}

当我调试时,我看到“()”的初始语句似乎不正确。另一种方法是将查询第一个元素分配给 myQuery 并从第二个元素开始增长。有没有一种优雅的方式来做到这一点?

4

1 回答 1

1

您可以指定一个整数值,并在循环中为每次迭代加 1。当它等于 1 时,您将初始值设置为 myQuery 字符串。

示例代码如下:

        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("your_account", "your_key"),true);

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("people");

            string myQuery = string.Empty;

            List<string> myConditionLists = new List<string>();
            myConditionLists.Add("Ben1");
            myConditionLists.Add("Ben2");
            myConditionLists.Add("Ben3");
            myConditionLists.Add("Ben4");
            myConditionLists.Add("Ben5");

            //specify an integer value
            int i = 0;

            foreach (string myCondition in myConditionLists)
            {
                i++;
                //if i == 1, specify the initial value to the myQuery string.
                if (i == 1) { myQuery = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.NotEqual, myCondition); }
                else
                {
                    myQuery = TableQuery.CombineFilters(
                        myQuery,
                        TableOperators.And,
                        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.NotEqual, myCondition)
                        );
                }
            }

            TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(myQuery);

            foreach (CustomerEntity entity in table.ExecuteQuery(query))
            {
                Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
                    entity.Email, entity.PhoneNumber);
            }


            Console.WriteLine("---completed---");
            Console.ReadLine();
        }

我的桌子:

在此处输入图像描述

测试结果:

在此处输入图像描述

于 2018-11-13T02:40:46.933 回答