사전을 반복하는 방법은 무엇입니까?
질문
나는 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 이하의 기능이며 위의 기능을 사용하면 여기에서 키 / 값의 정확한 유형을 사용할 수도 있습니다)
답변
경우에 따라 루프 구현에 의해 제공 될 수있는 카운터가 필요할 수 있습니다.이를 위해 LINQ는 다음을 수행 할 수있는 ElementAT를 제공합니다.
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
답변
열쇠 나 값을 따르는 지 여부에 따라 다릅니다 ...
MSDN 사전 (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 #에서 사전을 반복하는 여러 가지 방법이 있으며 가장 좋은 방법이 없습니다.그것은 필요성과 종종 맛에 따라 다릅니다.
가장 간단한 방법
foreach (var kvp in items)
{
// key is kvp.Key
doStuff(kvp.Value)
}
값만 (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는 또한 간결한 해결책을 제공합니다.
가치에 직접 반복합니다 (kvp.value보다 읽을 수있는 항목을 호출 할 수 있습니다) 그러나 키로 정렬
여기있어:
foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
doStuff(item)
}
이 예제에서 할 수있는 더 많은 실제 사용 사례가 있습니다. 특정 주문이 필요하지 않으면 "가장 간단한 방식"(위 참조)에 충실하십시오!
답변
C # 7.0 도입 Decronstrors를 도입했으며 .NET Core 2.0+ 응용 프로그램을 사용하는 경우 Struct KeyValuepair <>에는 이미 해독 ()이 이미 포함되어 있습니다.그래서 당신은 할 수 있습니다 :
var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}

최근댓글