我有一个班级:
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.
如何实现这一目标?
答案 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);