728x90

데이터베이스 = 파일 처리를 하기위한 도구

 

LINQ(Language INtegrated Query)

C# 언어에 통합된 데이터 질의 기능

프로그래밍에서 많은 부분을 차지하는 데이터 작업의 효율을 크게 향상

데이터 질의란 데이터 집합에서 원하는 데이터를 찾는 작업

데이터질의 기본 요소

from : 어떤 데이터집합에서

where : 어떤 조건으로

select : 어떤 항목을

 

15장

513페이지

var : 타입이 없이 변수 선언 가능

LINQ에서는 select를 가장 마지막에

 

516예제

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Linq;
 
namespace Linq_From
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 92645378110 };
 
            // 짝수만 LINQ로 출력
            var result = from n in numbers
                         where n % 2 == 0
                         orderby n
                         select n;
 
            foreach(int n in result)
            {
                Console.WriteLine(n);
            }
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Linq;
 
namespace Quiz_Gugudan
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[72];
            int k = 0;
 
            for(int i = 2; i <= 9; i++)
            {
                for(int j = 1; j <= 9; j++)
                {
                    numbers[k] = i * j;
                    k++;
                }
            }
 
            // LINQ
            var result = from n in numbers
                         where n % 3 == 0
                         select n;
 
            foreach(int n in result)
            {
                Console.WriteLine(n);
            }
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace LINQ_exam1
{
    // 객체, 정우성 : 186, 김태희 : 158,...
    class Profile
    {
        private string name;
        private int height;
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
        public Profile() { }
        public Profile(string name, int height)
        {
            Name = name;
            Height = height;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Profile[] arrProfile =
            {
                new Profile(){Name="정우성", Height=186 },
                new Profile("김태희"158),
                new Profile() { Name = "고현정", Height=172},
                new Profile("이문세"178),
                new Profile("하동훈"171)
            };
 
            // 작업
            // 특정 객체만 가지는 List
 
            List<Profile> profiles = new List<Profile>();
            // 키가 175 이하 배우만 수집
            foreach(Profile profile in arrProfile)
            {
                if (profile.Height < 175)
                    profiles.Add(profile);
            }
            // 람다
            profiles.Sort(
                (profile1, profile2) =>
                {
                    return profile1.Height - profile2.Height;
                }
            );
 
            foreach (var profile in profiles)
                Console.WriteLine("{0}, {1}", profile.Name, profile.Height);
 
            //LINQ 사용
            var myProfiles = from profile in arrProfile
                             where profile.Height < 175
                             orderby profile.Height
                             select profile;
 
            foreach (var profile in myProfiles)
                Console.WriteLine("{0}, {1}", profile.Name, profile.Height);
        }
    }
}
cs

 

람다식(Lambda Expression)

식 람다 (매개변수목록) => 식

 

람다식으로 무명함수 정의하기

무명함수(Anonymous Function) : 람다식으로 만드는 익명 메소드

무명함수를 작성하기 위해서는 먼저 대리자로 무명함수의 모습을 결정

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
 
namespace Lamda_easy
{
    class Program
    {
        delegate int MyDelegate(int a, int b);
 
        class Calculator
        {
            public int Plus(int a, int b)
            {
                return a + b;
            }
            public int Minus(int a, int b)
            {
                return a - b;
            }
        }
        static void Main(string[] args)
        {
            Calculator Calc = new Calculator();
            MyDelegate Callback;
 
            Callback = new MyDelegate(Calc.Plus);
            Console.WriteLine(Callback(34));
 
            Callback = (a, b) => a - b; //Minus
        }
    }
}
cs

 

소스가 길어질 때 -> 람다

람다는 소스를 축약시켜줌

 

문 형식의 람다식

람다식 바디를 식이 아닌 코드 블록으로 작성

 

Func 대리자와 Action 대리자

.NET 라이브러리에 사전 정의되어 있는 대리자

익명 메소드/무명 함수 정의를 위해 매번 대리자를 새롭게 정의하는 불편을 제거

일반화와 최대 16개 매개변수를 지원

Func 대리자 : 반환 값이 있는 익명 메소드/무명 함수용 대리자

Action 대리자 : 반환 값이 없는 익명 메소드/무명 함수용 대리자

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
 
namespace SimpleLambda
{
    delegate int calculate(int a, int b);
    class Program
    {
        static void Main(string[] args)
        {
            calculate calc = (a, b) => a + b;
            Console.WriteLine(calc(34));
            calc = (a, b) => a - b;
            Console.WriteLine(calc(34));
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace StatementLambda
{
    delegate void DoSomething();
    class Program
    {
        static void Main(string[] args)
        {
            DoSomething DoIt = () =>
            {
                Console.WriteLine("동작을 합니다~!!!");
            };
            DoIt();
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
 
namespace StatementLambda
{
    delegate void DoSomething();
    delegate string Concatenate(string[] args);
    class Program
    {
        static void Main(string[] args)
        {
            DoSomething DoIt = () =>
            {
                Console.WriteLine("동작을 합니다~!!!");
            };
            DoIt();
 
            Concatenate concat = (arr) =>
            {
                string result = "";
                foreach (string s in arr)
                    result += s;
 
                return result;
 
                Console.WriteLine(concat(args));
            };
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
 
namespace FuncTest
{
    class Program
    {
        // Func 대리자 - 간단하게 무명함수 만들기 위해서~!!!
        static void Main(string[] args)
        {
            Func<int> func1 = () => 10;
            Console.WriteLine(func1());
 
            Func<intint> func2 = (x) => x * 2;
            Console.WriteLine(func2(4));
 
            Func<doubledoubledouble> func3 = (x, y) => x / y;
            Console.WriteLine(func3(227));
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
 
namespace ActionTest
{
    class Program
    {
        // Action 대리자 - 간단하게 void형 익명함수를 만들고 사용하고 싶어서
        static void Main(string[] args)
        {
            Action act1 = () => Console.WriteLine("Action()");
            act1();
 
            int result = 0;
            Action <int> act2 = (x) => result = x * x;
            act2(3);
            Console.WriteLine(result);
 
            Action<doubledouble> act3 = (x, y) =>
            {
                double pi = x / y;
                Console.WriteLine($"{x} {y} : {pi}");
            };
            act3(22.07.0);
        }
    }
}
cs

 

from 절

where 절

orderby 절

select 절

group by 절

 

조인(Join)

두 데이터 원본을 연결하는 연산

각 데이터 원본에서 특정 필드가 일치하는 데이터끼리 연결

내부 조인 : 일종의 교집합

외부 조인

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace LINQ_exam2
{
    class Person
    {
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 배우 5명의 Person 배열
            Person[] arrPerson =
            {
                new Person() {Name="정우성", Height = 186},
                new Person() {Name="김태희", Height=158},
                new Person() {Name="고현정", Height=172},
                new Person() {Name="이문세", Height=178},
                new Person() { Name="하동훈", Height=171}
            };
            // 키가 170 이상인 배우만 모여있는 List를 만들어 봅시다.
            var result = from person in arrPerson
                         where person.Height > 170
                         orderby person.Name descending // 내림차순
                         select person;
 
            foreach (Person p in result)
                Console.WriteLine($"{p.Name} : {p.Height}");
 
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace LINQ_exam2
{
    class Person
    {
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 배우 5명의 Person 배열
            Person[] arrPerson =
            {
                new Person() {Name="정우성", Height = 186},
                new Person() {Name="김태희", Height=158},
                new Person() {Name="고현정", Height=172},
                new Person() {Name="이문세", Height=178},
                new Person() { Name="하동훈", Height=171}
            };
            // 키가 170 이상인 배우만 모여있는 List를 만들어 봅시다.
            var result = from person in arrPerson
                         where person.Height > 170
                         orderby person.Name descending // 내림차순
                         select new
                         {
                             Name = person.Name,
                             InchHeight = person.Height * 0.393
                         };
 
            foreach (var person in result)
                Console.WriteLine($"{person.Name} : {person.InchHeight}");
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Linq;
 
namespace FromFrom
{
    class Class
    {
        public string Name
        {
            get;
            set;
        }
        public int[] Score
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class[] arrClass =
            {
                new Class(){Name = "연두반", Score = new int[] {99807024 } },
                new Class(){Name = "분홍반", Score = new int[] {60458772 } },
                new Class(){Name = "파랑반", Score = new int[] {92308594 } },
                new Class(){Name = "노랑반", Score = new int[] {9088017 } }
            };
            // 60점 이하 점수 중 가장 낮은 점수를 출력해 주세요
            // 출력방법 : 낙제 : 반이름 {가장 낮은 점수} <---- 어떻게 LINQ로 만들어주세요
 
            var classes = from c in arrClass
                          from s in c.Score
                          where s < 60
                          orderby s
                          select new { c.Name, Lowest = s };
 
            foreach (var c in classes)
                Console.WriteLine($"낙제 : {c.Name} ({c.Lowest})");
        }
    }
}
cs

 

조인

내부조인

 

LINQ는 db가 아니라 메모리

 

외부조인

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
 
namespace LINQ_Join1
{
    class Profile
    {
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
    }
    class Product
    {
        public string Title
        {
            get;
            set;
        }
        public string Star
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Profile[] arrProfile =
            {
                new Profile(){Name="정우성", Height=186},
                new Profile(){Name="김태희", Height=158},
                new Profile(){Name="고현정", Height=171},
                new Profile(){Name="이문세", Height=178},
                new Profile(){Name="하하", Height=171}
            };
            Product[] arrProduct =
            {
                new Product(){Title = "비트", Star = "정우성"},
                new Product(){Title = "CF다수", Star = "김태희"},
                new Product(){Title = "아이리스", Star = "김태희"},
                new Product(){Title = "모래시계", Star = "고현정"},
                new Product(){Title = "Solo 예찬", Star = "이문세"}
            };
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Linq;
 
namespace LINQ_Join1
{
    class Profile
    {
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
    }
    class Product
    {
        public string Title
        {
            get;
            set;
        }
        public string Star
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Profile[] arrProfile =
            {
                new Profile(){Name="정우성", Height=186},
                new Profile(){Name="김태희", Height=158},
                new Profile(){Name="고현정", Height=171},
                new Profile(){Name="이문세", Height=178},
                new Profile(){Name="하하", Height=171}
            };
            Product[] arrProduct =
            {
                new Product(){Title = "비트", Star = "정우성"},
                new Product(){Title = "CF다수", Star = "김태희"},
                new Product(){Title = "아이리스", Star = "김태희"},
                new Product(){Title = "모래시계", Star = "고현정"},
                new Product(){Title = "Solo 예찬", Star = "이문세"}
            };
 
            var listProfile = from profile in arrProfile
                              join product in arrProduct
                              on profile.Name equals product.Star
                              select new
                              {
                                  Name = profile.Name,
                                  Work = product.Title,
                                  Height = profile.Height
                              };
 
            Console.WriteLine("내부 조인 결과");
            foreach (var profile in listProfile)
            {
                Console.WriteLine($"{profile.Name}:{profile.Work}:{profile.Height}");
            }
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Linq;
 
namespace LINQ_Join1
{
    class Profile
    {
        public string Name
        {
            get;
            set;
        }
        public int Height
        {
            get;
            set;
        }
    }
    class Product
    {
        public string Title
        {
            get;
            set;
        }
        public string Star
        {
            get;
            set;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Profile[] arrProfile =
            {
                new Profile(){Name="정우성", Height=186},
                new Profile(){Name="김태희", Height=158},
                new Profile(){Name="고현정", Height=171},
                new Profile(){Name="이문세", Height=178},
                new Profile(){Name="하하", Height=171}
            };
            Product[] arrProduct =
            {
                new Product(){Title = "비트", Star = "정우성"},
                new Product(){Title = "CF다수", Star = "김태희"},
                new Product(){Title = "아이리스", Star = "김태희"},
                new Product(){Title = "모래시계", Star = "고현정"},
                new Product(){Title = "Solo 예찬", Star = "이문세"}
            };
 
            var listProfile = from profile in arrProfile
                              join product in arrProduct
                              on profile.Name equals product.Star
                              select new
                              {
                                  Name = profile.Name,
                                  Work = product.Title,
                                  Height = profile.Height
                              };
 
            Console.WriteLine("내부 조인 결과");
            foreach (var profile in listProfile)
            {
                Console.WriteLine($"{profile.Name}:{profile.Work}:{profile.Height}");
            }
 
            // Outer Join을 수행합니다
            listProfile =
                from profile in arrProfile
                join product in arrProduct
                on profile.Name equals product.Star into ps
                from product in ps.DefaultIfEmpty(new Product()
                {
                    Title = "그런거 없음"
                })
                select new
                {
                    Name = profile.Name,
                    Work = product.Title,
                    Height = profile.Height
                };
 
            Console.WriteLine("외부 조인 결과");
            foreach (var profile in listProfile)
            {
                Console.WriteLine($"{profile.Name}:{profile.Work}:{profile.Height}");
            }
        }
    }
}
cs

 

도구 - Nuget 패키지 관리자 - 솔루션용 Nuget 패키지 관리

oracle managed Data Access

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Oracle_Connect
{
    class Program
    {
        static void Main(string[] args)
        {
            // 오라클 연결 문자열        
 
            string strConn = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xe)));User Id=hr;Password=hr;";
 
            // 오라클 연결
 
            OracleConnection conn = new OracleConnection(strConn);
 
            conn.Open();
 
            //...
 
            conn.Close();
        }
    }
}
cs

 

728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기