C #에서 사전을 반복하는 몇 가지 방법을 보았습니다. 표준적인 방법이 있습니까?
답변
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
답변
C #에서 일반 사전을 사용하려는 경우 다른 언어로 연관 배열을 사용하십시오.
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
또는 키 컬렉션 만 반복해야하는 경우
foreach(var item in myDictionary.Keys)
{
foo(item);
}
마지막으로, 값에만 관심이 있다면 :
foreach(var item in myDictionary.Values)
{
foo(item);
}
합니다 (참고를 타고 var
키워드는 선택의 C # 3.0 기능 이상, 당신은 또한 여기에 키 / 값의 정확한 유형을 사용할 수 있습니다)
답변
경우에 따라 for 루프 구현에서 제공 할 수있는 카운터가 필요할 수 있습니다. 이를 위해 LINQ는 ElementAt
다음을 지원합니다.
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
답변
키 또는 값 뒤에 있는지 여부에 따라 다릅니다.
MSDN Dictionary(TKey, TValue)
클래스 설명에서 :
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
답변
일반적으로 특정 컨텍스트없이 “최상의 방법”을 요구 하는 것은 최상의 색상이 무엇인지 묻는 것과 같습니다
.
한 손으로 많은 색상이 있으며 최상의 색상이 없습니다. 그것은 필요와 종종 맛에 달려 있습니다.
반면에 C #에서 Dictionary를 반복하는 방법은 여러 가지가 있으며 최선의 방법은 없습니다. 그것은 필요와 종종 맛에 달려 있습니다.
가장 간단한 방법
foreach (var kvp in items)
{
// key is kvp.Key
doStuff(kvp.Value)
}
값만 필요한 경우 (을 호출 할 수 item
있으며보다 읽기 쉽습니다 kvp.Value
).
foreach (var item in items.Values)
{
doStuff(item)
}
특정 정렬 순서가 필요한 경우
일반적으로 초보자는 사전의 열거 순서에 놀랐습니다.
LINQ는 순서 (및 기타 여러 가지)를 지정할 수있는 간결한 구문을 제공합니다.
foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
// key is kvp.Key
doStuff(kvp.Value)
}
다시 한 번만 값이 필요할 수 있습니다. LINQ는 또한 다음과 같은 간결한 솔루션을 제공합니다.
- 값을 직접 반복하십시오 (호출하기
item
쉽고보다 읽기 쉽습니다kvp.Value
) - 그러나 키로 정렬
여기있어:
foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
doStuff(item)
}
이 예제에서 수행 할 수있는 더 많은 실제 사용 사례가 있습니다. 특정 주문이 필요하지 않은 경우 “가장 간단한 방법”(위 참조)을 고수하십시오!
답변
나는 foreach가 표준 방법이라고 말하고 싶지만 분명히 당신이 찾고있는 것에 달려 있습니다.
foreach(var kvp in my_dictionary) {
...
}
찾고 계십니까?
답변
멀티 스레드 처리를 위해 큰 사전에서이를 시도 할 수도 있습니다.
dictionary
.AsParallel()
.ForAll(pair =>
{
// Process pair.Key and pair.Value here
});