C#/복습

4가지 Cullection (List,Queue,Stack,Dictionary)

Game Client Lee Hwanguk 2023. 1. 21. 20:55

#List<T>

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.list-1?view=net-7.0 

 

List<T> 클래스 (System.Collections.Generic)

인덱스로 액세스할 수 있는 강력한 형식의 개체 목록을 나타냅니다. 목록의 검색, 정렬 및 조작에 사용할 수 있는 메서드를 제공합니다.

learn.microsoft.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CullectionTest
{
    internal class App
    {
        public App()
        {
            //컬랙션 연습
            //1.인스턴스 생성
            List<Weapon> weapons = new List<Weapon>(); 
            Weapon weapon0= new Weapon("장검");
            //2.Add,Remove,Count (추가, 제거, 갯수)
            weapons.Add(weapon0);
            Console.WriteLine(weapons.Count); //List에 몇개 들어있는지(Count) 확인
            Weapon temp=weapons[0]; //장검
            Console.WriteLine("{0}, {1}", temp.GetHashCode(), weapon0.GetHashCode());
            Console.WriteLine(weapon0==temp); //true
            
            weapons.Add(new Weapon("단검"));
            Console.WriteLine(weapons.Count);
            Weapon temp0= weapons[1]; //단검
            Console.WriteLine(temp0==temp); //장검 !=단검 ->false

            //weapons.Add(100); //불가. weapons는 Weapon 타입만 가져오게 생성됨
            //3.index로 요소값 가져오기
            //4.Remove,pop,dequeue...
            //5.for, foreach
            

            for (int i=0; i<weapons.Count; i++)
            {
                if (weapons[i] != null) 
                { Console.WriteLine(weapons[i].name); 
                }
                else { Console.WriteLine("[     ]"); } //배열과 다르게 추가된 값만 보여줌 

            }

            foreach(Weapon obj in weapons)
            {
                if (obj != null) { Console.WriteLine(obj.name); }
                else
                {
                    Console.WriteLine("[    ]");//배열과 다르게 추가된 값만 보여줌 
                }
            }
            foreach(Object obj in weapons) 
            {
                Console.WriteLine(obj); // . 으로 접근 불가 
            }
            

        }
    }
}

#유용한 메서드

.Add(T)->개체를 List<T> 끝부분에 추가
.Clear() ->모두 삭제
.CopyTo(T[],int32)->배열의 지정된 인덱스(int32)부터 전체 복사
.Indexof(T) / .Indexof(T,int32) ->지정된 개체를 검색, (int32)에서부터 처음 접하는 인덱스 반환
.Remove(T) ->맨 처음 접하는 발견된 인덱스 제거 
.ToArray() ->배열에 복사
.ToString() ->문자열 반환

 

#Queue<T>

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.queue?view=net-7.0 

 

Queue 클래스 (System.Collections)

개체의 선입선출(FIFO) 컬렉션을 나타냅니다.

learn.microsoft.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CullectionTest
{
    internal class App
    {
        public App()
        {
            //컬랙션 연습
            //Queue (선입, 선출)
            Queue<int> q=new Queue<int>(); 

            //Add
            q.Enqueue(1); //Enqueue 추가
            q.Enqueue(2);
            q.Enqueue(3);

            //contains //요소가 있는지 확인 bool 타입
            bool q0=q.Contains(3); 
            Console.WriteLine(q0); //true

            //요소 가져오기(Peek)
            q.Peek();// 선입선출(1부터 나옴)
            Console.WriteLine(q.Peek()); //

            //Dequeue 요소를 제거함
            Console.WriteLine(q.Dequeue()); //Peek 와 다르게 제거한 후 가져온다 count로 확인
            Console.WriteLine(q.Count());

            //for문은 사용 불가, foreach문 가능
            foreach(Object que in q) //typq 은 Object형식
            {
                Console.WriteLine(que);
            }

        }
    }
}

#유용한 메서드

#Queue<T> 메서드
.Clear()->개체를 모두 제거
.Contains(Object)->Object가 있는지 확인(bool타입)
.Enqueue(Objecy)->끝부분에 추가
.Dequeue()->시작부분부터 제거
.Peek()->개체를 제거하지않고 반환
.ToArray()->새 배열에 복사

 

#Stack<T>

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.stack?view=net-7.0 

 

Stack 클래스 (System.Collections)

제네릭이 아닌 개체의 간단한 LIFO(Last In First Out: 마지막에 들어간 것부터 사용) 컬렉션을 나타냅니다.

learn.microsoft.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CullectionTest
{
    internal class App
    {
        public App()
        {
            //컬랙션 연습
            //Stack (후입, 선출)
            Stack<Weapon> weapons = new Stack<Weapon>();
            Weapon weapon0 = new Weapon("장검");
            Weapon weapon1 = new Weapon("단검");
            Weapon weapon2 = new Weapon("도끼");
            
            //Add
            weapons.Push(weapon0);
            weapons.Push(weapon1);
            weapons.Push(weapon2);

            //contains //요소가 있는지 확인 bool 타입
            weapons.Contains(weapon0); //Queue와 동일

            //요소 가져오기(Peek)
            Console.WriteLine( weapons.Peek().name); //후입 선출 , weapon2가 나옴

            //Dequeue 요소를 제거함 
            weapons.Pop(); //Queue의 Dequeue와 동일, 제거하고 가져온다


            //for문은 사용 불가, foreach문 가능
            foreach(Object weap in weapons)
            {
                Console.WriteLine( weap);
            }
            foreach (Weapon weap in weapons)
            {
                Console.WriteLine(weap.name);
            }

        }
    }
}

#유용한 메서드

#Stack<T> 메서드
.Clear()->개체를 모두 제거
.Contains(Object)->Object가 있는지 확인(bool타입)
.Push(Objecy)->끝부분에 추가
.Pop()->시작부분부터 제거
.Peek()->개체를 제거하지않고 반환
.ToArray()->새 배열에 복사

 

#Dictionary<T>

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.dictionary-2?view=net-7.0 

 

Dictionary<TKey,TValue> 클래스 (System.Collections.Generic)

키와 값의 컬렉션을 나타냅니다.

learn.microsoft.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CullectionTest
{
    internal class App
    {
        public App()
        {
            //컬랙션 연습
            //Dictionary (Key와Value)
            Dictionary<int,string>dic=new Dictionary<int,string>(); //key - int, value - string
            dic.Add(100,"장검");
            dic.Add(101, "단검"); //동일한 key값은 쓸수없음, value는 동일해도 무관
            dic.Add(102, null); //null값 추가 가능

            //contains
            Console.WriteLine( dic.ContainsKey(101)); //Key값으로 찾는다 ,bool타입, true or false

            //단일 요소값 가져오기
            string a=dic[102];
            Console.WriteLine( a );
            string b=dic[101];
            Console.WriteLine( b ); //key로 접근하여 value 출력, 반대도 될까?

            //int c=dic["장검"]; //value로는 접근이 안된다

            //Remove(key값으로 지움)
            dic.Remove(100);
            Console.WriteLine(dic.Count);

            //for문 사용 불가, foreach문 가능
            foreach (KeyValuePair<int,string>pair in dic) 
            {
                Console.WriteLine("{0},{1}",pair.Key,pair.Value);
            }
        }
    }
}

#유용한 메서드

#Dictionary<T>메서드
.Add(Tkey,TValue) ->키와 값을 사전에 추가
.Clear() ->모두 삭제
.Containskey(TKey)-> key값이 있는지 확인
.ContainsValue(TValue)-> value 값이 있는지 확인
.Remove(TKey)->키가 있는 값을 제거
.Remove(TKey,TValue)->키가 갖고있는 값 제거, value 복사