범위와 인덱스 그리고 슬라이싱 (Range, Index and Slicing)
2022. 2. 11. 00:00ㆍCSharp/Advance
반응형
범위와 인덱스는 시퀀스의 단일 요소 또는 범위에 액세스하기 위한 간결한 구문을 제공.
System.Index
: ^인덱스가 시퀀스의 끝을 기준으로 하도록 지정하는 끝 연산자 의 인덱스
System.Range
: ..범위의 시작과 끝을 피연산자로 지정하는 범위 연산자.
Data source
string[] words = new string[]
{
"The",
"quick",
"brown",
"fox",
"jumped",
"over",
"the",
"lazy",
"dog"
};
마지막 요소 찾기
string[] words = new string[]
{
// index from start index from end
"The", // 0 ^9
"quick", // 1 ^8
"brown", // 2 ^7
"fox", // 3 ^6
"jumped", // 4 ^5
"over", // 5 ^4
"the", // 6 ^3
"lazy", // 7 ^2
"dog" // 8 ^1
}; // 9 (or words.Length) ^0
Console.WriteLine($"The last word is {words[^1]}");
// output
The last word is dog
// 인덱스 변수 활용하기
System.Index index = ^1;
Console.WriteLine($"(with index variable) The last word is {words[index]}");
// output
(with index variable) The last word is dog
Range 를 통한 Slicing
// quick 부터 fox 까지 가져오기
string[] quickBrownFox = _words[1..4];
foreach(var word in quickBrownFox)
Console.WriteLine($"< {word} >");
// output
< quick >
< brown >
< fox >
Range 관련 연산자를 확인해 보면 1..4 이다. 시작요소는 포함되지만 끝요소는 포함되지 않는다.
즉 _words[1] 은 포함되고 _words[4] 는 포함되지 않는다.
1 <= quickBrownFox < 4
string[] allWords = words[..]; // contains "The" through "dog".
string[] firstPhrase = words[..4]; // contains "The" through "fox"
string[] lastPhrase = words[6..]; // contains "the, "lazy" and "dog"
foreach (var word in allWords)
Console.Write($"< {word} >");
Console.WriteLine();
foreach (var word in firstPhrase)
Console.Write($"< {word} >");
Console.WriteLine();
foreach (var word in lastPhrase)
Console.Write($"< {word} >");
Console.WriteLine();
// output
_words[..]
< The >< quick >< brown >< fox >< jumped >< over >< the >< lazy >< dog >
_words[..4]
< The >< quick >< brown >< fox >
_words[6..]
< the >< lazy >< dog >
관련영상
반응형
'CSharp > Advance' 카테고리의 다른 글
Parallel Programming (TPL) (0) | 2022.02.15 |
---|---|
Parallel Programming (Thread) (0) | 2022.02.14 |
LINQ Join Operators (조인연산자) (0) | 2022.02.10 |
LINQ Aggregator Operators (집계연산자) (0) | 2022.02.09 |
Linq 집합 연산자 (Set Operators) (0) | 2022.02.08 |