-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そして、関連するデータを入力することができます。

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.

これを達成する方法は?

4

1 に答える 1

2

最初に、すべての値をCustomerItem連結する方法を定義する必要があります。1 つの方法は、次のようにオーバーライド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);
于 2014-01-05T18:57:19.087 に答える