2014-01-05 1 views
-2

에 추가 할 수 있습니다.는 IEnumerable 항목 내가 클래스가 NameValueCollection은

이제 모든 항목을 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

Line [i] 란 무엇입니까? –

+0

@CoryNelson Pls는 업데이트 된 질문을 참조하십시오. – GilliVilla

+0

코드에서 주석에만 "줄"을 언급했습니다. 그게 뭐야? 왜 foreach와 함께 잘못 됐어? –

답변

2

먼저 CustomerItem의 모든 값을 연결하는 방법을 정의해야합니다. 단순히 CustomerItems 반복하여 대상 NameValueCollection 입력 할 수 있습니다 지금

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

: 한 가지 방법은 ToStringCustomerItem에서 무시하는 것

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

당신이 Dictionary<string, string>NameValueCollection를 교체하는 경우, 당신은 그것을 할 수 있습니다 심지어 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); 
관련 문제