[C#] Dictionary foreach for loop 예제

C#에서 Dictionary 컬렉션에 대해 foreach, for 반복문을 사용하는 방법에 대해 알아보도록 합시다.

Dictionary foreach

dictionary foreach
void BeomSang()
{
    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    dictionary.Add("b", "beom");
    dictionary.Add("s", "sang");

    Debug.WriteLine("foreach keyValuePair");
    foreach (KeyValuePair<string, string> keyValuePair in dictionary)
    {
        Debug.WriteLine($"key={keyValuePair.Key},value={keyValuePair.Value}");
    }

    Debug.WriteLine("foreach var");
    foreach (var keyValuePair in dictionary)
    {
        Debug.WriteLine($"key={keyValuePair.Key},value={keyValuePair.Value}");
    }

    Debug.WriteLine("for loop");
    for (int index = 0; index < dictionary.Count; index++)
    {
        Debug.WriteLine($"key={dictionary.ElementAt(index).Key},value={dictionary.ElementAt(index).Value}");
    }

    Debug.WriteLine("dictionary.keys");
    foreach (var key in dictionary.Keys)
    {
        Debug.WriteLine($"key={key}");
    }

    Debug.WriteLine("dictionary.values");
    foreach (var value in dictionary.Values)
    {
        Debug.WriteLine($"value={value}");
    }

    Debug.WriteLine("IEnumerable.Select");
    foreach (var value in dictionary.Select(x => x.Value))
    {
        Debug.WriteLine($"value={value}");
    }

    Debug.WriteLine("ToList.ForEach");
    dictionary.ToList().ForEach(
        keyValuePair => { Debug.WriteLine($"key={keyValuePair.Key},value={keyValuePair.Value}"); }
    );
}

딕셔너리의 foreach 반복문은, 컬렉션에 속한 각각의 키-밸류-페어에 대해 실행합니다. 그리하여 웬만한 경우에는 KeyValuePair<TKey, TValue>로 해결할 수 있습니다.

foreach (KeyValuePair<string, string> keyValuePair in dictionary)
{
    Debug.WriteLine($"key={keyValuePair.Key},value={keyValuePair.Value}");
}

그 외에도 var변수로 선언하는 방법, Keys 또는 Values만 반복하는 방법에 대해 안내해드렸습니다.

Dictionary for

딕셔너리 컬렉션의 카운트만큼 for 반복문을 실행할 수도 있습니다. 이때에는 Dictionary.ElementAt 메서드를 통해 해당 인덱스의 키 또는 밸류를 가져오도록 하였습니다.

for (int index = 0; index < dictionary.Count; index++)
{
    Debug.WriteLine($"key={dictionary.ElementAt(index).Key},value={dictionary.ElementAt(index).Value}");
}

그 외에도 Enumerable을 통해 키 또는 밸류를 가공하여 반복할 수도 있고, ToList 메서드로 변환한 다음 리스트에 대한 foreach 문을 수행하기도 합니다.

foreach (var value in dictionary.Select(x => x.Value))
{
    Debug.WriteLine($"value={value}");
}

dictionary.ToList().ForEach(
    keyValuePair => { Debug.WriteLine($"key={keyValuePair.Key},value={keyValuePair.Value}"); }
);

댓글