2010-02-09 8 views

답변

10

이렇게하는 데 직접적인 방법은 없습니다. 이것은 OrderedDictionary의 경우 인덱스 입니다. 실제 키를 원한다면 직접 추적해야합니다. 아마도 가장 간단한 방법은 색인 컬렉션에 키를 복사하는 것입니다 :

// dict is OrderedDictionary 
object[] keys = new object[dict.Keys.Count]; 
dict.Keys.CopyTo(keys, 0); 
for(int i = 0; i < dict.Keys.Count; i++) { 
    Console.WriteLine(
     "Index = {0}, Key = {1}, Value = {2}", 
     i, 
     keys[i], 
     dict[i] 
    ); 
} 

당신은 OrderedDictionary에 대한 액세스를 래핑하는 새로운 클래스로이 동작을 캡슐화 할 수있다.

+1

나는 동일했지만 한 번 참조 : OrderedDictionary 목록 = OrderItems에; 개체 strKey = 목록 [e.OldIndex]; DictionaryEntry dicEntry = new DictionaryEntry(); foreach (목록의 DictionaryEntry DE) { if (DE.Value == strKey) { dicEntry.Key = DE.Key; dicEntry.Value = DE.Value; } } –

+0

@ RedSwan : 색인은 어디에 있습니까? – testing

+2

색인은 확실히 열쇠가 아닙니다. * 열쇠는 반드시 "OrderedDictionary"의 별개의 구조입니다. – Conrad

35
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index); 
+1

에 의해 답변 됨 upvotes – Seb

+1

을 사용하면 충분합니다. using System.Linq; – testing

+0

이 코드를 사용하면 요소를 얻을 수 있습니다. 그러나 SO 질문과 마찬가지로 키와 가치를 얻는 방법은 무엇입니까? – testing

1

앞에서 언급 한 코드를 사용하여 키와 값으로 색인을 생성하는 확장 메서드를 만들었습니다.

public static T GetKey<T>(this OrderedDictionary dictionary, int index) 
{ 
    if (dictionary == null) 
    { 
     return default(T); 
    } 

    try 
    { 
     return (T)dictionary.Cast<DictionaryEntry>().ElementAt(index).Key; 
    } 
    catch (Exception) 
    { 
     return default(T); 
    } 
} 

public static U GetValue<T, U>(this OrderedDictionary dictionary, T key) 
{ 
    if (dictionary == null) 
    { 
     return default(U); 
    } 

    try 
    { 
     return (U)dictionary.Cast<DictionaryEntry>().AsQueryable().Single(kvp => ((T)kvp.Key).Equals(key)).Value; 
    } 
    catch (Exception) 
    { 
     return default(U); 
    } 
} 
+0

목표 색인/키가 사전에 없으면 기본값을 반환하려는 것이지만 값 비싼 방법을 선택했습니다. 해. 예외는 if/else와 같은 일반적인 제어 흐름 구조와 비교할 때 매우 비쌉니다. 예외 상황에 의존하는 것보다 범위를 벗어나는 인덱스와 존재하지 않는 키를 직접 확인하는 것이 훨씬 낫습니다. – Odrade

관련 문제