C # 사전은 어떻게됩니까? 키가 없으면 조회?
null을 확인하려고했지만 컴파일러는이 조건이 발생하지 않을 것이라고 경고합니다. 무엇을 찾아야합니까?
키 가 존재하는 경우 값을 얻으려면 다음을 사용하십시오 Dictionary<TKey, TValue>.TryGetValue
.
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
( ContainsKey
인덱서를 사용한 다음 키를 두 번 키로 보이게합니다. 이는 무의미합니다.)
참조 유형 을 사용 하더라도 null을 검사해도 작동하지 않습니다 Dictionary<,>
. null을 반환하는 대신 누락 된 키를 요청하면 인덱서 에서 예외가 발생합니다. (이 사이에 큰 차이가 Dictionary<,>
와 Hashtable
.)
사전에 KeyNotFound
키가없는 경우 사전에서 예외 가 발생합니다.
제안 된대로 ContainsKey
적절한 예방 조치입니다. TryGetValue
또한 효과적입니다.
이를 통해 사전은 널 (null) 값을보다 효과적으로 저장할 수 있습니다. 이런 식으로 동작하지 않으면 [] 연산자에서 널 결과를 검사하면 널값 또는 입력 키가 존재하지 않는 것으로 표시됩니다.
새 값을 추가하기 전에 확인하는 경우 다음 ContainsKey
방법을 사용하십시오 .
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
값이 존재하는지 확인하는 경우 TryGetValue
Jon Skeet의 답변에 설명 된 방법을 사용하십시오 .
값을 꺼내기 전에 Dictionary.ContainsKey (int key)를 확인해야합니다.
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}
ContainsKey 는 당신이 찾고있는 것입니다.
아마도 다음을 사용해야합니다.
if(myDictionary.ContainsKey(someInt))
{
// do something
}
null을 확인할 수없는 이유는 여기서 키가 값 유형이기 때문입니다.
도우미 클래스가 편리합니다.
public static class DictionaryHelper
{
public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
{
TVal val;
if( dictionary.TryGetValue(key, out val) )
{
return val;
}
return defaultVal;
}
}
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
Hope, this code helps you.
'IT story' 카테고리의 다른 글
Google Cloud Bigtable 및 Google Cloud Datastore (0) | 2020.08.03 |
---|---|
"최대 요청 길이를 초과했습니다"잡기 (0) | 2020.08.03 |
VIM에서 REPLACE 모드로 전환하는 방법 (0) | 2020.08.03 |
Amazon S3 Boto-폴더 생성 방법 (0) | 2020.08.03 |
JERSEY를 사용하여 입력 및 출력 이진 스트림? (0) | 2020.08.03 |