Machineboy空

C# Dictionary 딕셔너리 본문

언어/C#

C# Dictionary 딕셔너리

안녕도라 2025. 2. 6. 18:15

Dictionary란?

각 요소가 키(key)와 값(value)으로 이루어진 컬렉션이며,

키(key)를 전달하면 그에 연결된 값(value)이 반환됩니다.

  • key/value pair

Dictionary 생성

public static Dictionary<int, string> GetEmptyDictionary()
{
	return new Dictionary<int, string>();
}

Dictionary 초기화

public static Didctionary<int, string> GetExistingDictionary()
{
	var dictionary = new Dictionary<int, string>
    {
    	{1, "United States of America"},
        {55, "Brazil"},
        {91, "India"}
    };
    
    return dictionary;
}

Dictionary 포함 여부 확인 : ContainsKey(key)

public static bool CheckCodeExists(Dictionary<int, string> existingDictionary, int countryCode)
{
     return existingDictionary.ContainsKey(countryCode);
}

Dictionary 요소 추가 : Add(key, value)

public static Dictionary<int, string> AddCountryToDictionary(int countryCode, string countryName)
{
    var newDic = GetEmptyDictionary();
    newDic.Add(countryCode, countryName);
        
    return newDic;
}

Dictionary 요소 삭제 : Remove(key)

public static Dictionary<int, string> RemoveCountryFromDictionary(
        Dictionary<int, string> existingDictionary, int countryCode)
    {
        var newDic = existingDictionary;
        newDic.Remove(countryCode);
        return newDic;
    }

Dictionary 요소 갱신

public static Dictionary<int, string> UpdateDictionary(
        Dictionary<int, string> existingDictionary, int countryCode, string countryName)
{
     var newDic = existingDictionary;

     if(existingDictionary.ContainsKey(countryCode))
     {
          newDic[countryCode] = countryName;	// 참조하는 것만으로 생겨버리기 때문에, 있는지 체크
     }

     return newDic;
}

Dictionary 요소 순회 : foreach

public static string FindLongestCountryName(Dictionary<int, string> existingDictionary)
    {
        string longestName = "";
		
        // foreach 사용가능
        foreach(var a in existingDictionary)
        {
            if (a.Value.Length > longestName.Length)
            {
                longestName = a.Value;
            }
        }

        return longestName;
    }

Dictionary 정렬

Dictionary<char, int> dic = new Dictionary<char, int>();

var sortedDic = dic.OrderBy(item => item.Key).ToDictionary(x => x.Key, x => x.Value);

Dictionary 참조

public static class NucleotideCount
{
    public static IDictionary<char, int> Count(string sequence)
    {
        Dictionary<char, int> dic = new Dictionary<char,int>
        {
            {'A',0},
            {'C',0},
            {'G',0},
            {'T',0}
        };
        
        // Dictionary<char, int> dic = new Dictionary<char,int>() 이렇게 하면 참조만 한다고 공간이 생겨나지 않더라!
        
        foreach(char c in sequence)
        {
            if(c == 'A' || c == 'C' ||c == 'G'||c == 'T' )
            {
                dic[c]++;
            }else{
                throw new ArgumentException();
            }
        }

        return dic;
    }
}