I need to pass a JSON file to the vendor and the vendor gives the token back when I pass the JSON file. I have the following class in order to achieve that:
public class PayParam
{
public LineItemParam[] LineItems { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string CustomerId { get; set; }
public string CompanyName { get; set; }
}
public class LineItemParam
{
public string Sku { get; set; }
public string Description { get; set; }
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
}
I am constructing a JSON by passing values to the class like this:
var parameters = new PayParam();
MailingInfo IdData = scData.FindData();
string[] desc = {"Test1", "Test2", "Test3};
parameters = new PayParam
{
Phone = IdData.PhoneNumber,
Email = IdData.Email.ToUpper(),
CustomerId = "1234",
CompanyName = "TEST NAME",
},
LineItems = new LineItemParam[]
{
new LineItemParam
{
Sku = GetSKU(),
Description = "Test Desc",
UnitPrice = 12.00,
Quantity = 1
}
}
The problem is, I need to pass multiple lineItem for each description so I need to do something like this:
parameters = new PayParam
{
Phone = IdData.PhoneNumber,
Email = IdData.Email.ToUpper(),
CustomerId = "1234",
CompanyName = "TEST NAME",
},
foreach(var de in desc)
{
LineItems = new LineItemParam[]
{
new LineItemParam
{
Sku = GetSKU(),
Description = de,
UnitPrice = 12.00,
Quantity = 1
}
}
}
The above code is not working, its throwing syntax error. It only works if I put separate line item like this:
parameters = new PayParam
{
Phone = IdData.PhoneNumber,
Email = IdData.Email.ToUpper(),
CustomerId = "1234",
CompanyName = "TEST NAME",
},
LineItems = new LineItemParam[]
{
new LineItemParam
{
Sku = GetSKU(),
Description = "Test1",
UnitPrice = 12.00,
Quantity = 1
},
new LineItemParam
{
Sku = GetSKU(),
Description = "Test2",
UnitPrice = 12.00,
Quantity = 1
},
}
I want to pass these lineItems in a loop and not write them individually.
any help will be appreciated.
>Solution :
Just use LINQ Select method to transform collection of descriptions into array of LineItemParams, like below:
parameters = new PayParam
{
Phone = IdData.PhoneNumber,
Email = IdData.Email.ToUpper(),
CustomerId = "1234",
CompanyName = "TEST NAME",
LineItems = desc
.Select(de => new LineItemParam
{
Sku = GetSKU(),
Description = de,
UnitPrice = 12.00,
Quantity = 1
})
.ToArray(),
};