본문 바로가기
C++ 200제/코딩 IT 정보

C# List 사용법 10가지, 리스트 클래스 응용

by vicddory 2017. 8. 8.

일반적인 배열은 동적으로 크기 조절이 안 되지만, List는 그것이 가능합니다. 리스트를 사용하면 배열의 크기에 대해서 크게 신경 쓸 필요도 없습니다. 선형 리스트에 필요한 Key도 사용하지 않으면서 많은 기능을 제공합니다.

 

 

먼저, 개발자 취업을 목표로 독학하신다면 국비지원 제도도 적극 활용하시라 추천하면서 글 시작합니다.

https://kako.co.kr/1882/

 

국민내일배움카드 신청 방법 - 1mm

직업훈련 지원카드로, 실업자, 재직자, 특수형태근로종사자, 자영업자(일정 소득 이하) 등 취업여부나 직종에 관계없이 직업훈련이 필요한 분들에게 지원됩니다.

kako.co.kr

 

Key Point

List는 Generic이나 구조체로 간주합니다. 그래서 <> 사이에 자료형을 선언해야 합니다.

 

Add Value

using System.Collections.Generic;
 
class Program
{
static void Main()
{
List<int> list = new List<int>();
 
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7);
}
}

 

C# list add 함수
[C# 리스트] List Class 예제

 

위의 예제는 하나의 List에 불특정한 소수(Prime Number)를 추가하는 것을 나타냅니다.

Add를 이용해서 Value를 넣을 수 있습니다.

 

Loops

일반적인 배열처럼, List도 반복문을 접목해 사용할 수 있습니다.

경우에 따라선, List를 거꾸로 읽어서 사용자가 처리할 수도 있습니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
List<int> list = new List<int>();
 
list.Add(2);
list.Add(3);
list.Add(7);
 
// Loop through List with foreach.
foreach (int prime in list)
{
Console.WriteLine(prime);
}
 
// Loop with for.
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
}
}

 

C# list loops 함수
[C# 리스트] List Class 예제

 

Count Element

Key Point : 현재 사용 중인 리스트 내부의 요소 개수가 궁금할 땐 Count() 속성을 이용합니다.

 

Clear List

리스트 내부의 요소를 모두 지울 때 Clear() 메소드를 사용합니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
List<bool> list = new List<bool>();
list.Add(true);
list.Add(false);
list.Add(true);
Console.WriteLine(list.Count); // 3
 
list.Clear();
Console.WriteLine(list.Count); // 0
}
}

 

C# List Clear
[C# 리스트] List Class 예제

 

Copy array to List

생성자를 이용해서 만든 배열의 요소를 List에 매개변수로 전달해 복사할 수 있습니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
int[] arr = new int[3];
arr[0] = 2;
arr[1] = 3;
arr[2] = 5;
 
// Copy to List.
List<int> list = new List<int>(arr);
 
// 3 elements in List.
Console.WriteLine(list.Count);
}
}

 

C# List copy list
[C# 리스트] List Class 예제

 

Find Element

아래 예제는 List에서 원하는 요소를 검색하는 방법을 보여줍니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
// New list for example.
List<int> primes = new List<int>(new int[] { 2, 3, 5 });
 
// See if List contains 3.
foreach (int number in primes)
{
if (number == 3) // Will match once.
{
Console.WriteLine("Contains 3");
}
}
}
}

 

C# List find
[C# 리스트] List Class 예제

 

Join String List Example

String.Join을 이용해서 단어 사이에 ','가 찍히는 문자열을 만드는 예제입니다.

여러 개의 문자열을 구성할 때 유용하게 사용할 수 있습니다. List에서 문자열을 추출할 땐, ToArray를 이용합니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
// List of cities we need to join.
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
 
// Join strings into one CSV line.
string line = string.Join(",", cities.ToArray());
Console.WriteLine(line);
}
}

 

C# List string.join
[C# 리스트] List Class 예제

 

Get List from Keys in Dictonary

Key들의 값을 얻어낼 List를 생성하는 예입니다.

.Keys를 이용해서 Enumerable을 반환받기 때문에 가능합니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
// Populate example Dictionary.
var dict = new Dictionary<int, bool>();
dict.Add(3, true);
dict.Add(5, false);
 
// Get a List of all the Keys.
List<int> keys = new List<int>(dict.Keys);
 
foreach (int key in keys)
{
Console.WriteLine(key);
}
}
}

 

C# List dictionary
[C# 리스트] List Class 예제

 

Insert Element

이미 여러 요소를 보유한 List 중간에 새로운 값을 넣을 수 있습니다.

 

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
List<string> dogs = new List<string>();
 
dogs.Add("spaniel");
dogs.Add("beagle");
dogs.Insert(1, "dalmatian");
 
foreach (string dog in dogs)
{
Console.WriteLine(dog);
}
}
}

 

C# List insert
[C# 리스트] List Class 예제

 

Get range of Element

GetRange 메소드를 이용해서 범위 안의 요소를 추출할 수 있습니다.

LINQ의 Skip과 비슷한 면도 있습니다.

 

using System;
using System.Collections.Generic;
 
class Program{
static void Main()
{
List<string> rivers = new List<string>(new string[]
{
"nile",
"amazon", // River 2
"yangtze", // River 3
"mississippi",
"yellow"
} ); // Get rivers 2 through 3
 
List<string> range = rivers.GetRange(1, 2);
 
foreach (string river in range)
{
Console.WriteLine(river);
}
}
}

 

C# List get range
[C# 리스트] List Class 예제

 

 

댓글