프로그래밍(Programming)/C#

각종 Linq 함수들 Enumerable.Range, Where,Take, Any, Repeat, Distinct, Zip

3DMP 2018. 9. 7. 17:24



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
 
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace TestProject
{
 
    class t1s
    {
 
        static void Main(string[] args)
        {
            //지정된 된 범위 내의 정수 시퀀스를 생성 합니다.
            //Enumerable.Range 시작숫자부터 개수까지 숫자를 만드는 linq 함수
            int[] arr =  Enumerable.Range(110).Select(x => x * x).ToArray();
 
 
 
            foreach (var item in arr.Where(num => num % 2 == 1))  //linq 를 통해 배열에 확장 메소드 Where 를 사용 할 수 있다
            {
                Console.WriteLine(item);
            }
 
            Console.WriteLine("");
 
            foreach (var item in arr.Where(num => num % 2 == 1).Take(3))  //Take 는 앞에서부터 가져올 개수를 지정해준다
            {
                Console.Write(item + " " );
            }
            Console.WriteLine("");
 
 
            Console.WriteLine(   arr.Any(num => num == 1));     //Any : 값이 하나라도 존재하는가? , linq 에 있는 확장 메소드
 
            Console.WriteLine("");
 
 
 
            //3을 5번 생성
            int[] arr2 = Enumerable.Repeat(35).ToArray();
 
            foreach (var item in arr2)
            {
                Console.Write(item);
            }
 
 
            Console.WriteLine("");
            arr2[1]=5;
            arr2[3= 5;
            //중복된 값을 하나로 (중복 제거)
            foreach (var item in arr2.Distinct())
            {
                Console.Write(item+" ");
            }
 
 
            Console.WriteLine("\n\narr ");
            foreach (var item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("\n\narr2");
            foreach (var item in arr2)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("\n");
 
            //zip 두개의 컨테이너를 돌면서 원소가 양쪽 모두 존재할때까지 두 원소를 합친 컨테이너를 리턴
            var t3 = arr.Zip(arr2, (first, second) => "[ " + first + " : " + second + " ]" );
 
            Console.WriteLine("");
 
            foreach (var item in t3)
            {
                Console.Write(item + ",  ");
            }
        }
 
    }
}
 
 
 

cs



결과 


1

9

25

49

81


1 9 25

True


33333

3 5


arr

1 4 9 16 25 36 49 64 81 100


arr2

3 5 3 5 3



[ 1 : 3 ],  [ 4 : 5 ],  [ 9 : 3 ],  [ 16 : 5 ],  [ 25 : 3 ],



반응형