집게사장의 꿈

LINQ 메서드 본문

기타/C#

LINQ 메서드

Krapboss 2024. 7. 23. 01:59

 

 

 

 


시퀀스의 끝에 값을 추가하는

Append

public static System.Collections.Generic.IEnumerable<TSource> Append<TSource>
(this System.Collections.Generic.IEnumerable<TSource> source,
TSource element);


source : 참조할 값의 시퀀스
element : sources에 추가할 값

반환 : element로 끝나는 새로운 시퀀스

예외
ArgumentNullExceptionsource이(가) null인 경우

 

 

// 기존 List 에 N 숫자를 붙여서 새로운 시퀀스로 반환

// Creating a list of numbers
List<int> numbers = new List<int> { 1, 2, 3, 4 };

// Trying to append any value of the same type
numbers.Append(5);

// It doesn't work because the original list has not been changed
Console.WriteLine(string.Join(", ", numbers));

// It works now because we are using a changed copy of the original list
Console.WriteLine(string.Join(", ", numbers.Append(5)));

// If you prefer, you can create a new list explicitly
List<int> newNumbers = numbers.Append(5).ToList();

// And then write to the console output
Console.WriteLine(string.Join(", ", newNumbers));

// This code produces the following output:
//
// 1, 2, 3, 4
// 1, 2, 3, 4, 5
// 1, 2, 3, 4, 5

 

 


IEnumerable 의 요소를 지정된 형식으로 캐스팅하는

Cast[보류]

Enumerable.Cast<TResult>(IEnumerable)


형식 매개 변수
TResultsource의 요소를 캐스팅할 형식입니다.
매개 변수
sourceIEnumerableTResult 형식으로 캐스팅할 요소가 들어 있는 IEnumerable입니다.
반환
IEnumerable<TResult>
지정된 형식으로 캐스트된 소스 시퀀스의 각 요소가 들어 있는 IEnumerable<T>입니다.
예외
ArgumentNullExceptionsource이(가) null인 경우
InvalidCastException시퀀스의 요소를 TResult 형식으로 캐스팅할 수 없는 경우

+지연된 실행이 이루어진다.

 

 

*ArrayList로 추가한 object를 String으로 캐스팅하여 사용하는 구문

System.Collections.ArrayList fruits = new System.Collections.ArrayList();
fruits.Add("mango");
fruits.Add("apple");
fruits.Add("lemon");

IEnumerable<string> query =
    fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);

// The following code, without the cast, doesn't compile.
//IEnumerable<string> query1 =
//    fruits.OrderBy(fruit => fruit).Select(fruit => fruit);

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

// This code produces the following output:
//
// apple
// lemon
// mango

 

 


두 시퀀스를 연결하는

Concat

public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource>
(this System.Collections.Generic.IEnumerable<TSource> first
, System.Collections.Generic.IEnumerable<TSource> second);

* 두 시퀀스를 연결합니다.

first : 연결받을 시퀀스
second : 연결될 시퀀스

반환
IEnumerable<TSource>
두 입력 시퀀스의 연결된 요소가 들어 있는 IEnumerable<T>입니다.

예외
ArgumentNullExceptionfirst 또는 second가 null인 경우

+ 지연된 실행이 이루어

 

예시 1

List<object> list = new List<object>
{
    "123",
    "1234",
    "12345"
};

List<object> list2 = new List<object>
{
    "123",
    "1234",
    "12345"
};

var qurey = list.Concat(list2);

/* 즉시 실행되는 법
List<object> qurey = list.Concat(list2).ToList();
*/

foreach(var i in qurey) Console.WriteLine(i);

 

예시 2

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

static Pet[] GetCats()
{
    Pet[] cats = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };
    return cats;
}

static Pet[] GetDogs()
{
    Pet[] dogs = { new Pet { Name="Bounder", Age=3 },
                   new Pet { Name="Snoopy", Age=14 },
                   new Pet { Name="Fido", Age=9 } };
    return dogs;
}

public static void ConcatEx1()
{
    Pet[] cats = GetCats();
    Pet[] dogs = GetDogs();

    IEnumerable<string> query =
        cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));

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

// This code produces the following output:
//
// Barley
// Boots
// Whiskers
// Bounder
// Snoopy
// Fido

 

 


반복되는 단일 값의 시퀀스를 생성하는

Repeat

public static System.Collections.Generic.IEnumerable<TResult> Repeat<TResult> (TResult element, int count);

예외
ArgumentOutOfRangeExceptioncount 가 0보다 작습니다.

 

IEnumerable<string> strings =
    Enumerable.Repeat("I like programming.", 15);

foreach (String str in strings)
{
    Console.WriteLine(str);
}

/*
 This code produces the following output:

 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
 I like programming.
*/

 

 


시퀀스 요소를 반전하는

Reverse

public static System.Collections.Generic.IEnumerable<TSource> Reverse<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

예외
ArgumentNullExceptionsource이(가) null인 경우

char[] apple = { 'a', 'p', 'p', 'l', 'e' };

char[] reversed = apple.Reverse().ToArray();

foreach (char chr in reversed)
{
    Console.Write(chr + " ");
}
Console.WriteLine();

/*
 This code produces the following output:

 e l p p a
*/

 


 

지정된 범위의 시퀀스를 생성하는

Range

 

public static System.Collections.Generic.IEnumerable<int> Range (int start, int count);

예외
ArgumentOutOfRangeExceptioncount 가 0보다 작습니다.

 

기본

// Generate a sequence of integers from 1 to 10
// and then select their squares.
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
*/

 

 


 

요소가 비어있는 경우 지정된 값을 반환하는

DefaultIfEmpty

DefaultIfEmpty<TSource>(IEnumerable<TSource>)
지정된 시퀀스의 요소를 반환하거나, 시퀀스가 비어 있으면 형식 매개 변수의 기본값을 반환합니다.

예외
ArgumentNullExceptionsource이(가) null인 경우


DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)
지정된 시퀀스의 요소를 반환하거나, 시퀀스가 비어 있으면 singleton 컬렉션의 지정된 값을 반환합니다.

+지연된 실행

 

 

*DefaultIfEmpty<TSource>(IEnumerable<TSource>)

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void DefaultIfEmptyEx1()
{
    List<Pet> pets =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };

    foreach (Pet pet in pets.DefaultIfEmpty())
    {
        Console.WriteLine(pet.Name);
    }
}

/*
 This code produces the following output:

 Barley
 Boots
 Whiskers
*/
List<int> numbers = new List<int>();

foreach (int number in numbers.DefaultIfEmpty())
{
    Console.WriteLine(number);
}

/*
 This code produces the following output:

 0
*/

 

 

* DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void DefaultIfEmptyEx2()
{
    Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };

    List<Pet> pets1 =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };

    foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet))
    {
        Console.WriteLine("Name: {0}", pet.Name);
    }

    List<Pet> pets2 = new List<Pet>();

    foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet))
    {
        Console.WriteLine("\nName: {0}", pet.Name);
    }
}

/*
 This code produces the following output:

 Name: Barley
 Name: Boots
 Name: Whiskers

 Name: Default Pet
*/

 


지정된 요소의 첫번째를 반환하는

FirstOrDefault

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)
조건을 충족하는 시퀀스의 첫 번째 요소를 반환하거나, 이러한 요소가 없으면 지정된 기본값을 반환합니다.

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource)
시퀀스의 첫 번째 요소를 반환하거나 시퀀스에 요소가 없는 경우 지정된 기본값을 반환합니다.

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)
시퀀스에서 특정 조건에 맞는 첫 번째 요소를 반환하거나, 이러한 요소가 없으면 기본값을 반환합니다.

FirstOrDefault<TSource>(IEnumerable<TSource>)
시퀀스의 첫 번째 요소를 반환하거나, 시퀀스에 요소가 없으면 기본값을 반환합니다.

 

*지정된 조건의 첫번째 요소를 반환하지만, 없을 경우 기본값을 반환한다.

List<int> months = new List<int> { };

// Setting the default value to 1 after the query.
int firstMonth1 = months.FirstOrDefault();
if (firstMonth1 == 0)
{
    firstMonth1 = 1;
}
Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1);

// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int firstMonth2 = months.DefaultIfEmpty(1).First();
Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);

/*
 This code produces the following output:

 The value of the firstMonth1 variable is 1
 The value of the firstMonth2 variable is 1
*/

 

*string 기본값을 반환하는 

string[] names = { "Hartono, Tommy", "Adams, Terry",
                     "Andersen, Henriette Thaulow",
                     "Hedlund, Magnus", "Ito, Shu" };

string firstLongName = names.FirstOrDefault(name => name.Length > 20);

Console.WriteLine("The first long name is '{0}'.", firstLongName);

string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30);

Console.WriteLine(
    "There is {0} name longer than 30 characters.",
    string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a");

/*
 This code produces the following output:

 The first long name is 'Andersen, Henriette Thaulow'.
 There is not a name longer than 30 characters.
*/

 

 


키 값을 기준으로 기본 같음 비교 연산자를 통해 두 시퀀스 요소를 연관하는

Join

public static System.Collections.Generic.IEnumerable<TResult>
Join<TOuter,TInner,TKey,TResult> (
this System.Collections.Generic.IEnumerable<TOuter> outer,
System.Collections.Generic.IEnumerable<TInner> inner,
Func<TOuter,TKey> outerKeySelector,
Func<TInner,TKey> innerKeySelector,
Func<TOuter,TInner,TResult> resultSelector);

 

System.Collections.Generic.IEnumerable<TInner> inner, outer와 연관시킬 시퀀스
Func<TOuter,TKey> outerKeySelector, outer에서 같음을 판단할 값을 반환하는 대리자
Func<TInner,TKey> innerKeySelector, inner에서 같음을 판단할 값을 반환하는 대리자
Func<TOuter,TInner,TResult> resultSelector); 두 키값이 같은 경우 결과값을 반환하는 대리자

 

 class Person
 {
     public string Name { get; set; }
 }

 class Pet
 {
     public string Name { get; set; }
     public Person Owner { get; set; }
 }
 internal class GroupBy // 웰컴 키트 
 {
     static void Main(string[] args)
     {
         Person magnus = new Person { Name = "Hedlund, Magnus" };
         Person terry = new Person { Name = "Adams, Terry" };
         Person charlotte = new Person { Name = "Weiss, Charlotte" };

         Pet barley = new Pet { Name = "Barley", Owner = terry };
         Pet boots = new Pet { Name = "Boots", Owner = terry };
         Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
         Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

         List<Person> people = new List<Person> { magnus, terry, charlotte };
         List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };

         // Create a list of Person-Pet pairs where
         // each element is an anonymous type that contains a
         // Pet's name and the name of the Person that owns the Pet.
         var query =
             people.Join(pets,                   //people와 Join할 시퀀스
                         person => person.Name,  //people의 key 값
                         pet => pet.Owner.Name,  //pet 의 key 값
                         (person, pet) =>        //두 개의 키값이 동일하다면, 지정한 형식으로 결과값을 반환
                             new { OwnerName = person.Name, Pet = pet.Name });

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

 

 

+사용자 정의 비교 연산자 사용 가능

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

 

 


출처

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

 

Enumerable.Aggregate 메서드 (System.Linq)

시퀀스에 누적기 함수를 적용합니다. 지정된 시드 값은 초기 누적기 값으로 사용되고 지정된 함수는 결과 값을 선택하는 데 사용됩니다.

learn.microsoft.com

 

'기타 > C#' 카테고리의 다른 글

LINQ 집합  (0) 2024.07.23
LINQ 집계함수  (0) 2024.07.23
LINQ 메서드 GroupBy  (1) 2024.07.23
C# LINQ 쿼리 키워드  (0) 2024.07.21
C# LINQ 소개  (0) 2024.07.21