๐ŸŽฎ Unity Study/C#

[C#] List ๊ฐ™์€ Enumerable ํด๋ž˜์Šค์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋“ค

ibelieveinme 2023. 4. 26. 13:13
728x90

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable?view=net-7.0 

 

Enumerable Class (System.Linq)

Provides a set of static (Shared in Visual Basic) methods for querying objects that implement IEnumerable<T>.

learn.microsoft.com

List ๋Š” IEnumerable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋ฐ›๊ณ  ์žˆ๋‹ค. IEnumerable์€ Enumerator๋ฅผ ๊ฐ–๊ณ ์žˆ๋‹ค. ๋ฐ˜๋ณต์—์„œ ์ˆœ์„œ๋Œ€๋กœ ํ•˜๋‚˜์”ฉ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ์„ ๋•Œ IEnumerable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

*IEnumerable: Enumerator์—๊ฒŒ ๋‹ค์Œ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ ํ•˜๋‚˜์”ฉ ๋„˜๊ฒจ์ฃผ๋Š” '์—ญํ• '์„ ํ•จ.

*Enumerator: ๋ช‡๋ฒˆ์งธ๊นŒ์ง€ ์ฝ์—ˆ๋Š”์ง€์— ๋Œ€ํ•œ state ๊ฐ’์„ ์ €์žฅํ•จ. MoveNext(), Current() ํ•จ์ˆ˜ ๋ฐ property๋ฅผ ๊ฐ–๊ณ ์žˆ์Œ.

                      - MoveNext() ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ๋ฐ›์œผ๋ฉด ๋‹ค์Œ ์ˆœ๋ฒˆ์œผ๋กœ ์ด๋™.

                      - Current๋ฅผ ์š”๊ตฌํ•  ๋• ํ•ด๋‹น ์ˆœ๋ฒˆ์˜ ๊ฐœ์ฒด๋ฅผ ๋ฆฌํ„ดํ•จ.

 

* Where

List<string> fruits =
    new List<string> { "apple", "passionfruit", "banana", "mango",
                    "orange", "blueberry", "grape", "strawberry" };

IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}
/*
 This code produces the following output:

 apple
 mango
 grape
*/

 

* ToList

string[] fruits = { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };

List<int> lengths = fruits.Select(fruit => fruit.Length).ToList();

foreach (int length in lengths)
{
    Console.WriteLine(length);
}

/*
 This code produces the following output:

 5
 12
 6
 5
 6
 9
 5
 10
*/

 

* Max

double?[] doubles = { null, 1.5E+104, 9E+103, -2E+103 };

double? max = doubles.Max();

Console.WriteLine("The largest number is {0}.", max);

/*
 This code produces the following output:

 The largest number is 1.5E+104.
*/

 

* Select

string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

...

728x90