-3

我有一堂课:

 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; }
    }

然后我有一个:

public IEnumerable<CustomerItem> CustomerItems {get; set;}

我能够得到CustomerItems相关数据的填充。

现在,我想将所有项目添加CustomerItemsNameValueCollection.

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.

如何做到这一点?

4

1 回答 1

2

首先,您需要定义CustomerItem应如何连接所有值。一种方法是ToString覆盖CustomerItem

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

NameValueCollection现在您可以通过简单地迭代来填充目标CustomerItems

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

如果你NameValueCollection用 a替换Dictionary<string, string>,你甚至可以通过使用 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);
于 2014-01-05T18:57:19.087 回答