Ad

How To Apply For-loop In Between String Data To Create An Order In Shopify Through Api

- 1 answer

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

in this code i want to iterate line items(varientid_arr[0], quantity_arr[0] ) for creating order with multiple products in shopify. i want to apply for loop in line items only within string.

Ad

Answer

Use Linq's Select method:

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

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

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

The key is that you're using select to build a new string out of each element in the varientid_arr list. But since you're using 2 lists, you need access to the index at each element of varientid so that you can get the correct quantity item. Select has an overload for this where the lambda accepts the item at each iteration and the index.

DISCLAIMER: I would not recommend this. Any time you want to template out strings doing complicated things like this, use more readable ways and more robust methods. Don't just jam it all into a single statement like this.

You might consider breaking each part of the string into a function, then building the string by calling each function and putting them together.

Here's an incomplete example.

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

string data = $"{{ ""order"": {orderJson}, ""customer"": {customerJson}, ""financial_status"": {financialStatusJson} }}";
Ad
source: stackoverflow.com
Ad