I have a class:
public class CustomerItem
{
public CustomerItem(IEnumerable<SomeProperty> someProperties,
IEnumerable<Grade> grades,
decimal unitPrice, int quantity, string productCode)
{
SomeProperties = someProperties;
Grades = grades;
UnitPrice = unitPrice;
Quantity = quantity;
ProductCode = productCode;
}
public string ProductCode { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public IEnumerable<Grade> Grades { get; set; }
public IEnumerable<SomeProperty> SomeProperties { get; set; }
}
And then I have a:
public IEnumerable<CustomerItem> CustomerItems {get; set;}
and I am able to get the CustomerItems
populated with relevant data.
Now, I would like to add all the items from CustomerItems
to a NameValueCollection
.
NameValueCollection target = new NameValueCollection();
// I want to achieve
target.Add(x,y); // For all the items in CustomerItems
// where - x - is of the format - Line1 - for first item like "Line" + i
// "Line" is just a hardcodedvalue to be appended
// with the respective item number in the iteration.
// where - y - is the concatenation of all the values for that specific line.
How to achieve this?
First you need to define how all the values in
CustomerItem
should be concatenated. One way would be to overrideToString
inCustomerItem
:Now you can fill in the target
NameValueCollection
by simply iterating overCustomerItems
:If you replace
NameValueCollection
with aDictionary<string, string>
, you can do it even by just using LINQ: