2012-12-05 3 views
4

나는 다음과 같은 코드를 가지고 : 이제사전 목록을 반복하는 방법은 무엇입니까?

List<Dictionary<string, string>> allMonthsList = new List<Dictionary<string, string>>(); 
while (getAllMonthsReader.Read()) { 
    Dictionary<string, string> month = new Dictionary<string, string>(); 
    month.Add(getAllMonthsReader["year"].ToString(), 
    getAllMonthsReader["month"].ToString()); 
    allMonthsList.Add(month); 
} 
getAllMonthsReader.Close(); 

내가 개월의 모든을 통해 루프를 시도하고,이 같은 :

foreach (Dictionary<string, string> allMonths in allMonthsList) 

가 어떻게 키 값에 액세스 할을? 내가 뭔가 잘못하고 있는거야?

답변

9
foreach (Dictionary<string, string> allMonths in allMonthsList) 
{ 
    foreach(KeyValuePair<string, string> kvp in allMonths) 
    { 
     string year = kvp.Key; 
     string month = kvp.Value; 
    } 
} 

일반적으로 BTW 년은 1 개월 이상입니다. 여기에 조회가 필요하거나, 모든 달을 저장하는 데 Dictionary<string, List<string>>이 필요합니다.

설명 일반 사전 Dictionary<TKey, TValue>IEnumerable 인터페이스를 구현합니다.이 인터페이스는 컬렉션을 반복하는 열거자를 반환합니다. MSDN에서 : 열거 목적

, 사전에 각 항목 같은 값 및 해당 키를 나타내는 KeyValuePair<TKey, TValue> 구조를 처리한다. 항목이 반환되는 순서는 정의되지 않습니다.

C# 언어의 foreach 문에는 컬렉션의 각 요소 유형이 필요합니다. Dictionary<TKey, TValue>은 키와 값의 집합이므로 요소 유형은 키 유형이나 값 유형이 아닙니다. 대신 요소 유형은 키의 KeyValuePair<TKey, TValue>이며 값 유형입니다.

+0

미상의'allMnths' 어디에서 온? –

+0

나중에 1 달이 필요하다는 것을 알고 있습니다. :) 그러나 'Error 'System.Collections.Generic.Dictionary '에'Key '에 대한 정의가없고'Key '확장 메서드가 없습니다. 'System.Collections.Generic.Dictionary '형식의 첫 번째 인수를 수락 할 수 있습니다 (사용 지시문이나 어셈블리 참조가 누락 되었습니까?) \t '문자열을 사용하려고 할 때. –

+0

@ lazyberezovsky 나는 그가 문법 오류가 있다고 생각한다. –

3
var months = allMonthsList.SelectMany(x => x.Keys); 

당신이 모든 키의 단순 열거 제발하는 것처럼 그런 다음 IEnumerable<string>을 반복 할 수 있습니다.

+0

또 다른 방법으로,'KeyValuePair'를 통해 직접 반복하려는 경우'allMonthsList.SelectMany (x => x)'를 할 수 있습니다. –

1

디자인이 잘못되었습니다. 사전에 한 쌍을 사용하는 것은 의미가 없습니다. 사전 목록을 사용할 필요가 없습니다.

class YearMonth 
{ 
    public string Year { get; set; } 
    public string Month { get; set; } 
} 

List<YearMonth> allMonths = List<YearMonth>(); 
while (getAllMonthsReader.Read()) 
{ 
    allMonths.Add(new List<YearMonth> { 
          Year = getAllMonthsReader["year"].ToString(), 
          Month = getAllMonthsReader["month"].ToString() 
             }); 
} 

getAllMonthsReader.Close(); 

사용으로 :

이 시도 위 닷넷 프레임 워크 4.0 이상을 사용하는 경우,

foreach (var yearMonth in allMonths) 
{ 
    Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Year, yearMonth.Month); 
} 

또는, 당신은 튜플

List<Tuple<string, string>> allMonths = List<Tuple<string, string>>(); 
while (getAllMonthsReader.Read()) 
{ 
    allMonths.Add(Tuple.Create(getAllMonthsReader["year"].ToString(), 
           getAllMonthsReader["month"].ToString()) 
       ); 
} 

getAllMonthsReader.Close을 사용할 수 있습니다();

그런 다음 사용

foreach (var yearMonth in allMonths) 
{ 
    Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Item1, yearMonth.Item2); 
} 
+1

반드시 의미있는 것은 아닙니다 - 런타임까지 필드의 개수를 모르는 경우는 어떨까요? ? 모든 제안은 컴파일 타임에 지식을 필요로합니다 (월 목록이 단지 Jan-Dec 일 경우 작동하지만 입력에서 읽은 다른 데이터가있는 반복 월 목록 인 경우는 작동하지 않음). –

관련 문제