유니티3D 프로그래밍

C# 3주차 2일 수업 내용 : LINQ 및 람다, EVENT(21.03.23) 본문

C#/수업내용

C# 3주차 2일 수업 내용 : LINQ 및 람다, EVENT(21.03.23)

tjdgus9955 2021. 3. 23. 11:22

LINQ 및 람다

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");

            //컬렉션 생성
            List<Item> items = new List<Item>();

            //Item 객체 생성
            Item item1 = new Item("장검");
            Item item2 = new Item("단검");
            Item item3 = new Item("활");
            Item item4 = new Item("장검");
            //컬렉션 추가
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);
            items.Add(item4);

            //컬렉션에서 item 객체의 이름이 xxx인것을 찾으세요
            //Linq : Find + 람다
            Item foundItem = items.Find(x => x.GetName() == "장검");
            if(foundItem != null)
            {
                Console.WriteLine(foundItem.GetName());
            }
            else
            {
                Console.WriteLine("아이템이 없습니다.");
            }

            Console.WriteLine();
            //만약에 같은 이름의 요소가 있다면 모드 찾아서 출력하세요
            //Linq : Where + 람다
            IEnumerable<Item> foundNames = items.Where(x => x.GetName() == "장검");
            foreach(Item item in foundNames)
            {
                Console.WriteLine(item.GetName());
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public class Item
    {
        private string name;
        public Item(string name)
        {
            this.name = name;
        }

        public string GetName()
        {
            return this.name;
        }
    }
}

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Study01
{
    public class Book
    {
        public string ID { get; set; }
        public string Title { get; set; }
        public DateTime PublishDate { get; set; }
        public string Genre { get; set; }

        public override string ToString()
        {
            return string.Format("{0} {1} {2} {3}", this.ID, this.Title, this.Genre, this.PublishDate);
        }
    }

    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            //Book book2 = new Book() { ID = "bk109", Title = "이것이 C#이다", Genre = "Computer", PublishDate = new DateTime(2001, 1, 1)};
            //Console.WriteLine(book2.ToString());

            //컬렉션 인스턴스화 
            List<Book> books = new List<Book>();

            //books.Find(delegate (Book book) {
            //    return book.ID == "bk109";
            //});
            var book1 = new Book()
            {
                ID = "bk109",
                Title = "어린왕자",
                Genre = "Novel",
                PublishDate = new DateTime(2002, 01, 01)
            };

            var book2 = new Book()
            {
                ID = "bk108",
                Title = "콩쥐팥쥐",
                Genre = "Fairytale",
                PublishDate = new DateTime(2002, 01, 01)
            };

            Console.WriteLine(book1.ToString());

            books.Add(book1);
            books.Add(book2);

            List<Book> list = books.FindAll(FindComputer);
            //요소의 수 
            Console.WriteLine(list.Count);
            //출력 
            foreach (Book book in list)
            {
                Console.WriteLine(book.ToString());
            }
        }

        private bool FindComputer(Book book)
        {
            if (book.Genre == "Novel")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Study01
{

    public class DinoComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                else
                {
                    // If x is null and y is not null, y
                    // is greater.
                    return -1;
                }
            }
            else
            {
                if (y == null)
                {
                    return 1;
                }
                else
                {
                    int retval = x.Length.CompareTo(y.Length);

                    if (retval != 0)
                    {
                        // If the strings are not of equal length,
                        // the longer string is greater.
                        //
                        return retval;
                    }
                    else
                    {
                        return x.CompareTo(y);
                    }
                }
            }
        }
    }

    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            List<string> dinosaurs = new List<string>();

            dinosaurs.Add("Pachycephalosaurus");
            dinosaurs.Add("Parasauralophus");
            dinosaurs.Add("Amargasaurus");
            dinosaurs.Add("Galimimus");
            dinosaurs.Add("Mamenchisaurus");
            dinosaurs.Add("Deinonychus");
            dinosaurs.Add("Oviraptor");
            dinosaurs.Add("Tyrannosaurus");

            int herbivores = 5;
            Display(dinosaurs);

            DinoComparer dc = new DinoComparer();

            Console.WriteLine("\nSort a range with the alternate comparer:");
            dinosaurs.Sort(0, herbivores, dc);
            Display(dinosaurs);

            Console.WriteLine("\nBinarySearch a range and Insert \"{0}\":",
                "Brachiosaurus");

            int index = dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc);

            if (index < 0)
            {
                dinosaurs.Insert(~index, "Brachiosaurus");
                herbivores++;
            }

            Display(dinosaurs);

        }

        private static void Display(List<string> list)
        {
            Console.WriteLine();
            foreach (string s in list)
            {
                Console.WriteLine(s);
            }
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Study01
{
     
    public class App
    {
        public delegate void SendMessage(string message);

        
        public App()
        {
            Console.WriteLine("App");

            //대리자 변수 선언 및 초기화
            SendMessage del1 = this.Hello;
            SendMessage del2 = this.Hi;

            //대리자 호출
            del1("홍길동");
            del2("임꺽정");
            Console.WriteLine("-------------------");
            //대리자 변수 선언 및 초기화
            SendMessage del = del1 = del2;
            del("장길산");
            Console.WriteLine("-------------------");
            SendMessage del3 = ((name) => Console.WriteLine("안녕하세요, {0}님", name));

            del += del3;
            del("고길동");
            Console.WriteLine("-------------------");

            del -= del2;
            del("둘리");
            Console.WriteLine("-------------------");
        }

        public void Hello(string name)
        {
            Console.WriteLine("Hello, {0}", name);
        }

        public void Hi(string name)
        {
            Console.WriteLine("Hi, {0}", name);
        }
        
    }
}

 

Delegate 사칙연산

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Study01
{
     
    public class App
    {
        public delegate void ThereIsAFire(string location);
        
        public App()
        {
            Console.WriteLine("App");

            //대리자 변수 선언 및 초기화
            ThereIsAFire fire = new ThereIsAFire(this.Call119);
            fire += new ThereIsAFire(this.ShotOut);
            fire += new ThereIsAFire(this.Escape);
            fire("우리집");

            fire -= new ThereIsAFire(this.Escape);
            fire("우리집");
        }

        public void Call119(string location)
        {
            Console.WriteLine("소방서죠? 불났어요! 주소는 {0}", location);
        }
        public void ShotOut(string location)
        {
            Console.WriteLine("피하세요! {0}에 불났어요!", location);
        }
        public void Escape(string location)
        {
            Console.WriteLine("{0}에서 나갑시다!", location);
        }

    }
}

Event 핸들러

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace Study01
{
    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }

    public class App
    {
        public class Counter
        {
            public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
            private int threshold;
            private int total;
            public Counter(int passedThreshold)
            {
                this.threshold = passedThreshold;
            }

            public void Add(int x)
            {
                this.total += x;
                Console.WriteLine("{0}/{1}", this.total, this.threshold);
                if(this.total >= this.threshold)
                {
                    //이벤트 매개 객체 생성 + 데이터 셋업
                    ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                    args.Threshold = threshold;
                    args.TimeReached = DateTime.Now;

                    //대리자 선언 및 초기화
                    EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
                    handler(this, args);
                
                }
            }
           
        }
        
        public class Button
        {
            public Action onPress; // 대리자 변수 선언

            public Button()
            {

            }

            public void Press()
            {
                this.onPress();
            }
        }
        public App()
        { 
            Console.WriteLine("App");

            Button btn = new Button();
            Counter counter = new Counter(10);
            counter.ThresholdReached += CounterThresholdReached;
            //대리자 초기화
            btn.onPress = () =>
             {
                 while(true)
                 {
                     Thread.Sleep(500);
                     counter.Add(1);
                 }
             };
            btn.Press();

        }

        private void CounterThresholdReached(object sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
            Environment.Exit(0);
        }

    }
}