c# 개념잡기 - 3.0 새 기능


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace NewFeature30
{
    /// <summary>
    /// 자동구현 속성 예제를 위한 클래스 
    /// </summary>
    public class TestClass
    {
        public string TempValue {get; set;}
    }

    /// <summary>
    /// 확장메소드 예제를 위한 클래스
    /// </summary>
    public static class EMClass
    {
        public static int ToInt32Ext(this string s)
        {
            return Int32.Parse(s);
        }
        public static int ToInt32Static(string s)
        {
            return Int32.Parse(s);
        }
    }  

    // 람다
    delegate int EasyDelegate(int i);




    [TestFixture]
    public class NewFeatureTest
    {
        /// <summary>
        /// var 지역변수에 대한 테스트
        /// </summary>
        [Test]
        public void testVar()
        {
            var int1=100;
            int int2=100;
            Assert.AreEqual(int1, int2);

            var str1 = "Hello World";
            string str2 = "Hello World";
            Assert.AreEqual(str1, str2);

            var arr1 = new int[] { 1, 2, 3 };
            int[] arr2 = new int[] { 1, 2, 3 };
            Assert.AreEqual(arr1, arr2);

            var sb1 = new StringBuilder("Kimstar");
            StringBuilder sb2 = new StringBuilder("Kimstar");
            Assert.AreNotEqual(sb1, sb2);
            Assert.AreEqual(sb1.ToString(), sb2.ToString());
        }


        /// <summary>
        /// 익명 타입 : 
        /// new 연산자를 통해 생성되는 인스턴스는
        /// 코드 블록 안에 선언된 속성을 갖는 "클래스"가 된다.
        /// </summary>
        [Test]
        public void testAnonymous()
        {
            var anonymousType = new { 정수값 = 100, 문자열값 = "Hello World" };
            Assert.AreEqual(anonymousType.정수값, 100);
            Assert.AreEqual(anonymousType.문자열값, "Hello World");
            Assert.AreEqual(anonymousType.정수값+100, 200);
        }



        /// <summary>
        /// 자동 구현 속성 : get / set의 코드를 줄임
        /// </summary>
        /// <example>
        /// <code>
        /// public string TempValue {get; set;}
        /// </code>
        /// </example>
        [Test]
        public void testGetSet()
        {
            TestClass tc = new TestClass();
            tc.TempValue = "Kimstar";       // set
            string temp = tc.TempValue;     // get

            Assert.AreEqual(temp, "Kimstar");
        }


        /// <summary>
        /// 이니셜라이저
        /// </summary>
        [Test]
        public void testInitializer()
        {
            // 객체 이니셜라이저
            TestClass tc = new TestClass { TempValue = "kimstar" };
            Assert.AreEqual(tc.TempValue, "kimstar");


            // 컬렉션 이니셜라이저
            List<TestClass> tcList = new List<TestClass> {
                new TestClass{ TempValue = "test1" },
                new TestClass{ TempValue = "test2" },
                new TestClass{ TempValue = "test3" }
            };
            Assert.AreEqual(tcList.ElementAt(0).TempValue, "test1");
        }



        /// <summary>
        /// 확장메서드
        /// 확장 메서드는 static class에 static method로 선언 하여,
        /// instance메소드를 호출 하듯이 사용하여야 함.
        /// http://www.towis.net/2690132
        /// </summary>
        [Test]
        public void testExtensionMethod()
        {
            string s = "9";
            int i = s.ToInt32Ext();              // 확장 메서드   
            int j = EMClass.ToInt32Static(s);    // 일반 적으로 사용하는 방법  
            Assert.AreEqual(i, j);
        }


        public static int SomeMethod(int i)
        {
            return i * i;
        }

        /// <summary>
        /// 람다식
        /// </summary>
        /// <example>
        /// <code>
        /// delegate int EasyDelegate(int i);
        /// 
        /// public static int SomeMethod(int i)
        /// {
        ///     return i * i;
        /// }
        /// </code>
        /// </example>
        /// <code>
        [Test]
        public void testLabmdaExpression()
        {
            // => 기준으로 왼쪽 파라메터가 전달되어, 오른쪽 코드가 구현됨
            EasyDelegate ed = z => z + 10;
            int lamdaResult = ed(100);
            Assert.AreEqual(lamdaResult, 110);





            // 메서드를 이용한 함수 생성
            Func<int, int> fun1 = SomeMethod;
            Assert.AreEqual(fun1(3), 9);

            // 익명 메서드를 이용한 함수 생성
            Func<int, int> fun2 = delegate(int i) { return i * i; };
            Assert.AreEqual(fun2(3), 9);

            // 람다식을 이용한 함수 생성
            Func<int, int> fun3 = i => i * i;
            Assert.AreEqual(fun3(3), 9);





            // 필터를 사용 예제
            // RemoveAll 의 반환값 : System.Collections.Generic.List<T>에서 제거한 요소의 수입니다.
            // 
            List<int> numbers1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            int effectedCnt1 = numbers1.RemoveAll(
                                                    delegate(int num)
                                                    {
                                                        return num % 2 == 0;

                                                    }
                                                );
            Assert.AreEqual(effectedCnt1, 7);

            // 필터를 사용 예제
            List<int> numbers2 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            int effectedCnt2 = numbers2.RemoveAll(i => i % 2 == 0);
            Assert.AreEqual(effectedCnt2, 7);

            // Map를 사용 예제
            // ConvertAll 반환값 : 현재 System.Collections.Generic.List<T>에서 변환된 요소를 포함하는 대상 형식의 System.Collections.Generic.List<T>입니다.
            List<int> numbers3 = new List<int> { 1, 2, 3, 4 };
            List<int> squares = numbers3.ConvertAll(i => i * i);
            Console.WriteLine("----ConvertAll----");
            foreach (int i in squares)
            {
                Console.WriteLine(i.ToString());
            }
            Assert.AreEqual(squares[3], 16);

            // Reduce를 사용 예제
            // Aggregate 반환값 : 최종 누적기 값입니다.
            // Aggregate : 집합적인, 총계의
            List<int> numbers4 = new List<int> { 1, 2, 3, 4 };
            int accumlate = numbers4.Aggregate(10, (c, i) => c + i);  // 최초의 c=10이 됨, i에는 1,2,3,4가 반복대입되며 이때마다 c=c+i 됨.
            Assert.AreEqual(accumlate, 10 + 1 + 2 + 3 + 4);

        }
    }



    class Class1
    {
        static void Main(string[] args)
        {

            // page 28 : select -----------------
            // Select 반환값 :  해당 요소가 source의 각 요소에 대해 변형 함수를 호출한 결과인 System.Collections.Generic.IEnumerable<T>입니다.
            int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var result1_1 = numbers.Select(n => n*n);
            var result1_2 = from n in numbers
                          select n*n;
            Console.WriteLine("page 28 : select -----------------");
            foreach (var n in result1_2)
            {
                Console.WriteLine(n.ToString());
            }

            // page 28 : select -----------------
            // 익명타입 사용시 예제
            var result2_1 = numbers.Select(n => new { Number = n, IsEven = (n % 2 == 0) });
            var result2_2 = from n in numbers
                          select new { Number = n, IsEven = (n % 2 == 0) };
            Console.WriteLine("page 28 : select -----------------");
            foreach (var n in result2_2)
            {
                Console.WriteLine("Number {0} is Even? : {1}", n.Number, n.IsEven);
            }


            // page 29 : where -----------------
            var result3_1 = numbers.Where(n => n < 7).Select(n => n);
            var result3_2 = from n in numbers
                            where n < 7
                            select n;
            Console.WriteLine("page 29 : where -----------------");
            foreach (var n in result3_2)
            {
                Console.WriteLine(n.ToString());
            }

            // page 29 : orderby -----------------
            var result4_1 = numbers.OrderBy(n => n);
            var result4_2 = from n in numbers
                            orderby n
                            select n;
            Console.WriteLine("page 29 : orderby -----------------");
            foreach (var n in result4_2)
            {
                Console.WriteLine(n.ToString());
            }

            // page 30 : orderbydescending -----------------
            var result5_1 = numbers.OrderByDescending(n => n);
            var result5_2 = from n in numbers
                            orderby n descending
                            select n;
            Console.WriteLine("page 30 : orderbydescending -----------------");
            foreach (var n in result5_2)
            {
                Console.WriteLine(n.ToString());
            }



            // page 30 : innerJoin -----------------
            // north wind 추가 : http://zmeun.tistory.com/15
            // linq sample : http://msdn2.microsoft.com/ko-kr/vcsharp/aa336746(en-us).aspx
            //var innerJoinQuery = from category in categories
            //                     join prod in products on category.ID equals prod.CategoryID
            //                     select new { Category = category.ID, Product = prod.Name };
            //Console.WriteLine("page 30 : innerJoin -----------------");
            //foreach (var item in innerJoinQuery)
            //{
            //    Console.WriteLine(item.Product, item.Category);
            //}

        }
    }
}

 

광고

댓글 남기기