Post

[C#] Lec 11 - 람다 표현식, LINQ

[C#] Lec 11 - 람다 표현식, LINQ

람다식 (Lambda Expression)

  • 익명 메소드를 사용하기 위해 주로 사용하게 됨.
1
2
3
4
5
6
delegate int Calculate (int a, int b) ;
static void Main(){
  Calculator calc = (int a, int b)=> a+b;
  calc = (a, b) = >a+b; // 같은 방법
}
  • 복잡한 람다식의 경우
1
2
3
4
5
6
7
8
delegate int DoSomething();

static void Main() {
  DoSomething Doit = () => { // 여러 줄의 람다식 표현
    Console.WriteLine("asdf");
    return 0;
  }
}

람다식의 활용 (Func, Action)

  • delegate 선언과 delegate(int a) 등 delegate 키워드 활용없이 Func, Action을 이용하여 람다식 활용가능
1
2
3
4
5
6
7
static void Main() {
  Func<int> func1 = () => 1;
  Func<int, int> func2 = (x) => x+10; //가장 오른쪽만 result, 나머지는 매개변수 입력형식
  int result = 0;
  Action<int> action1 = (x) => result + x;
  Action<int, int> action 2 = (x, y) => result + x*y;
}
  • delegate 키워드를 이용할 필요 x, Return 값이 필요하면 Func, 반환형식이 void이면 Acion.

LINQ (Language Integrated Query)

  • 데이터 읽고 거르고 정렬하는 작업은 프로그램에서 수시로 진행됨
  • 편리하게 하기 위해 LINQ 활용. 간단한 질의를 통해 데이터 취합, 정리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collecitons;
usgin System.Collections.Generic;

namespace TestProject {
  class Profile
  {
    public string Name {get; set;}
    public int Height {get; set;}
  }
  Profile[] arrProfile = {
  new Profile(){Name=“철수”, Height = 180},
  new Profile(){Name=“영희”, Height = 160},
  new Profile(){Name=“짱구”, Height = 170},
  new Profile(){Name=“흰둥”, Height = 160},
  new Profile(){Name=“맹구”, Height = 181},
  new Profile(){Name=“뚱이”, Height = 177}
  };
  var profiles = from profile in arrProfile
                 where profile.Height<175
                 orderby profile.Height
                 select profile;
}
  • 표준 연산자 (Method) 의 형태로도 사용가능
1
var profiles = arrProfile.Where(i=>i.Height<175).Orderby(i=>i.Height);
This post is licensed under CC BY 4.0 by the author.