IEnumerable items to be added to NameValueCollection

1.2k Views Asked by At

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?

1

There are 1 best solutions below

0
On

First you need to define how all the values in CustomerItem should be concatenated. One way would be to override ToString in CustomerItem:

public override string ToString()
{
    // define the concatenation as you see fit
    return String.Format("{0}: {1} x {2}", ProductCode, Quantity, UnitPrice);
}

Now you can fill in the target NameValueCollection by simply iterating over CustomerItems:

var index = 1;
var target = new NameValueCollection();
foreach (var customerItem in CustomerItems)
{
    target.Add(String.Format("Line {0}", i), customerItem.ToString());
    i++;
}

If you replace NameValueCollection with a Dictionary<string, string>, you can do it even by just using LINQ:

var target = CustomerItems.Select((item, index) => new 
                              { 
                                  Line = String.Format("Line {0}", index + 1), 
                                  Item = item.ToString()
                              })
                          .ToDictionary(i => i.Line, i => i.Item);