如何在字符串数据之间应用 for 循环以通过 api 在 shopify 中创建订单

how to apply for-loop in between string data to create an order in shopify through api

string data = @"  
               {
                ""order"": {  
                 ""line_items"": [
                    {
                    ""variant_id"":" + varientid_arr[0] +@",
                    ""quantity"":" + quantity_arr[0] + @"
                    }
                   ],
                    ""customer"": {
                                  ""id"": 2750996643918
                                  },
                    ""financial_status"": ""pending""
                    }
                 }
                 ";

在此代码中,我想迭代订单项(varientid_arr[0]、quantity_arr[0])以在 shopify 中创建包含多个产品的订单。我只想在字符串中的行项目中申请循环。

使用 Linq 的 Select 方法:

string data = @"  
              {
                ""order"": {  
                  ""line_items"": [" +

                    string.Join(",\n", varientid_arr.Select((varientid, index) =>
                    @"{
                      ""variant_id"":" + varientid +@",
                      ""quantity"":" + quantity_arr[index] + @"
                     }") +

                  @"],
                  ""customer"": {
                    ""id"": 2750996643918
                  },
                  ""financial_status"": ""pending""
                }
              }";

关键是您正在使用 select 从 varientid_arr 列表中的每个元素构建一个新字符串。但是由于您使用的是 2 个列表,因此您需要访问 varientid 的每个元素的索引,以便您可以获得正确数量的项目。 Select 对此有一个重载,其中 lambda 在每次迭代和索引中接受项目。

免责声明:我不推荐这个。任何时候你想要模板化字符串来做这样复杂的事情,使用更易读的方式和更健壮的方法。不要像这样把所有内容都塞进一个语句中。

您可以考虑将字符串的每个部分分解为一个函数,然后通过调用每个函数并将它们放在一起来构建字符串。

这是一个不完整的例子。

string orderJson = GetOrderJson(varrientid_arr, quantity_arr);
string customerJson = GetCustomerJson();
string financialStatusJson = GetFinancialStatus();

string data = $"{{ ""order"": {orderJson}, ""customer"": {customerJson}, ""financial_status"": {financialStatusJson} }}";