要添加到NameValueCollection的IEnumerable项

时间:2014-01-05 18:12:48

标签: c# linq ienumerable namevaluecollection

我有一个班级:

 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

现在,我想将CustomerItems中的所有项目添加到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.

如何实现这一目标?

1 个答案:

答案 0 :(得分: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替换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);