수업 011 (04.20 2020) List<>

2020. 4. 21. 00:02
728x90

* List<type> 변수 = new List<type>();

ex) List<string> itemNameList = new List<string>();

* list.Add("");

* list[i] = "";

* list.Remove("");                 // List<T>에서 맨 처음 발견하는 특정 개체를 지움

* string 변수 = list.Find( x => x == "")

ex)

foundItemName = itemNameList.Find(x => x == targetItemName);

 

1. App.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study._012
{
    class App
    {
        public App()
        {
            // 리스트 객체 생성
            List<string> list = new List<string>();
 
            // 값을 추가
            list.Add("hong");
 
            // 리스트의 길이
            Console.WriteLine(list.Count);      // output: 1
            Console.WriteLine();
 
            // 인덱스로 접근해서 가져오거나 설정할수 있음
            list[0= "lim";
 
            // index가 0보다 작은 경우 또는 index가 System.Collections.Generic.List`1.Count보다 크거나 같은 경우 (error)
            // list[1] = "lim";
 
            list.Add("jang");
            Console.WriteLine(list.Count);      // output: 2
            Console.WriteLine();
 
            // for문으로 요소를 출력
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            // output: lim jang
            Console.WriteLine("---------");
 
            foreach (string name in list)
            {
                Console.WriteLine(name);
            }
            // output: same as for statement result
            Console.WriteLine("---------");
 
            // lim 문자열과 같은 요소를 찾기
            string foundName = "";
 
            foreach (string name in list)
            {
                if (name == "lim")
                {
                    // 찾았다
                    foundName = name;
                }
                break;
            }
            Console.WriteLine("Found Name: {0} \n", foundName);
 
            string foundName2 = list.Find(x => x == "lim");
            Console.WriteLine("Found Name 2: {0} \n", foundName2);
 
            list.Remove("lim");
 
            foreach (string name in list)
            {
                Console.WriteLine("Name: {0} \n", name);
                // output: Name: jang
            }
 
            Console.WriteLine("list.Count: {0} \n"list.Count);        //length
            // output: list.Count: 1
        }
    }
}

 

 

 

 

2. Result

728x90

BELATED ARTICLES

more