본문 바로가기

C#

C# List Dictionary 예제 사과 딸기

반응형

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);
            }
        }
    }
}

반응형

'C#' 카테고리의 다른 글

C# 상속  (0) 2021.07.23
C# age = (value > 0) ? value : age;  (0) 2021.07.23
C# Dictionary 예제  (0) 2021.07.23
test2 list클래스 예제  (0) 2021.07.23
C# 주차장 요금계산 시스템  (0) 2021.07.22