집게사장의 꿈

LINQ 특정 요소를 가져오는 메서드 본문

카테고리 없음

LINQ 특정 요소를 가져오는 메서드

Krapboss 2024. 7. 23. 23:52

시퀀스의 각 요소를 새 형식으로 반환하는

Select

반환
IEnumerable<TResult>
해당 요소가 source의 각 요소에 대해 변형 함수를 호출한 결과인 IEnumerable<T>입니다.
예외
ArgumentNullExceptionsource 또는 selector가 null인 경우

 

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 }
*/

 

IEnumerable<int> squares =
    Enumerable.Range(1, 10).Select(x => x * x);

foreach (int num in squares)
{
    Console.WriteLine(num);
}
/*
 This code produces the following output:

 1
 4
 9
 16
 25
 36
 49
 64
 81
 100
*/

 

 

 


조건에 따른 시퀀스 요소의 필터링하는

Where

public static System.Collections.Generic.IEnumerable<TSource> Where<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);

예외
ArgumentNullExceptionsource 또는 predicate가 null인 경우

 

문자열의 길이가 6보다 작은 요소를 반환

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
*/

 

int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 };

IEnumerable<int> query =
//각 요소의 index[순서] 를 같이 받는다.
    numbers.Where((number, index) => number <= index * 10);

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

 0
 20
 15
 40
*/

 

 


시퀀스의 지정한 수만큼 건너뛰어 반환하는

Skip

public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);

예외
ArgumentNullExceptionsource은 null입니다.
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

Console.WriteLine("All grades except the first three:");
foreach (int grade in grades.Skip(3))
{
    Console.WriteLine(grade);
}

/*
 This code produces the following output:

All grades except the first three:
 56
 92
 98
 85
*/

 


조건에 맞는 시퀀스 요소가 아닐 때까지 요소를 무시하는

SkipWhile

public static System.Collections.Generic.IEnumerable<TSource> SkipWhile<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);

예외
ArgumentNullExceptionsource 또는 predicate가 null인 경우

 

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> lowerGrades =
    grades
    .OrderByDescending(grade => grade)
    .SkipWhile(grade => grade >= 80);

Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

 

 

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> lowerGrades =
    grades
    //.OrderByDescending(grade => grade)
    .SkipWhile(grade => grade >= 80);

Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

 

 


 

시작 위치로부터 연속된 요소를 받아오는

Take

예외
ArgumentNullException source이(가) null인 경우

 

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> topThreeGrades =
    grades.OrderByDescending(grade => grade).Take(3);

Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
    Console.WriteLine(grade);
}
/*
 This code produces the following output:

 The top three grades are:
 98
 92
 85
*/

 

 


조건에 부합하지 않을 때까지의 요소를 반환하는

TakeWhile

반환
IEnumerable<TSource>
입력 시퀀스에서 요소가 테스트를 더 이상 통과하지 않는 위치보다 앞에 나오는 요소가 들어 있는 IEnumerable<T>입니다.

예외
ArgumentNullExceptionsource 또는 predicate가 null인 경우
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

IEnumerable<string> query =
    fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}

/*
 This code produces the following output:

 apple
 banana
 mango
*/

 

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

IEnumerable<string> query =//현재 배열의 index 순서를 받는다.
    fruits.TakeWhile((fruit, index) => fruit.Length >= index);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}

/*
 This code produces the following output:

 apple
 passionfruit
 banana
 mango
 orange
 blueberry
*/

 

 

 


중복을 제거하는

Distinc

반환
IEnumerable<TSource>
소스 시퀀스의 고유 요소가 들어 있는 IEnumerable<T>입니다.
예외
ArgumentNullExceptionsource이(가) null인 경우

 

List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
    Console.WriteLine(age);
}

/*
 This code produces the following output:

 Distinct ages:
 21
 46
 55
 17
*/

 

 

+사용자 정의 가능

https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.distinct?view=net-8.0