2012-10-14 4 views
0

사전에서 참조 된 마지막 색인을 찾는 방법이 있습니까? 예를 들어,사전에서 마지막 색인 참조 결정

"Temp"를 변수로 저장하지 않고 검색하는 방법이 있습니까?

+1

사전 클래스에는 이러한 기능이 없습니다. –

답변

2

는 코드

MyDic dic = new MyDic(); 
    dic.Add("1", "one"); 
    dic.Add("2", "two"); 
    dic.Add("3", "three"); 

    dic["1"] = "1one"; 

    dic["2"] = dic.LastKey; // LastKey : "1" 

    dic["3"] = dic.LastKey; // LastKey : "2"; 
0

아니요.이 작업을 저장하는 것은 거의 없습니다 (매우 이상한 요구 사항입니다). 직접해야합니다. 당신이 일반 사전에 갈하지 않는 이유는

0

을에

public class MyDic : Dictionary<String, String> 
{ 
    public string LastKey { get; set; } 

    public String this[String key] 
    { 
     get 
     { 
      LastKey = key; 
      return this.First(x => x.Key == key).Value; 
     } 
     set 
     { 
      LastKey = key; 
      base[key] = value; // if you use this[key] = value; it will enter an infinite loop and cause stackoverflow 
     } 
    } 

그런 다음 자신의 사전 구현 :

public class GenericDictionary<K, V> : Dictionary<K, V> 
{ 
    public K Key { get; set; } 

    public V this[K key] 
    { 
     get 
     { 
      Key = key; 
      return this.First(x => x.Key.Equals(key)).Value; 
     } 
     set 
     { 
      Key = key; 
      base[key] = value; 
     } 
    } 
} 

사용법 :

Dictionary<string, string> exampleDic; 
... 
exampleDic["Temp"] = "ASDF" 
var key = exampleDic.Key;