C#

C# List Dictionary 예제 사과 딸기

하이브 Hive 2021. 7. 23. 14:34
반응형

namespace test2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> fruits = new List<string>() { "사과", "딸기", "사과", "바나나", "바나나", "포도" };
            // <"과일", 갯수> 딕셔너리 선언
            Dictionary<string, int> fruitCount = new Dictionary<string, int>();

            foreach (var item in fruits)

            {
                if (fruitCount.ContainsKey(item)) // 과일이 fruitCount Key에 있으면
                    fruitCount[item]++; //과일 Key의 값++

                else
                    fruitCount.Add(item, 1); //fruitCount에 새로운 Key추가
            }

            foreach (var item in fruitCount)
            {
                Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
            }
        }
    }
}

반응형