블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

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
반응형

Category

Recent Post

Recent Comment

Archive

'.Net Project/.Net C#'에 해당되는 글 69

  1. 2009.08.20 102장 윈폼(Windows Form)
  2. 2009.08.20 101장 프로젝션
  3. 2009.08.19 100장 쿼리표현식(LINQ)
  4. 2009.08.19 99장 람다식
2009. 8. 20. 18:05 .Net Project/.Net C#
반응형
 윈폼(Windows Form)
그래픽 환경에서 화면을 구성하고 사용자와 통신하는 가장 기본적인 부품이 바로 윈도우
닷넷에서는 윈도우를 폼이라고 칭하며, 폼은 System.Windows.Form네임스페이스에 Form이라는 이름의 클래스로 정의되어 있으며, 클래스 안에 폼과 관련된 수많은 프로퍼티 가 정의 되어 있고, 폼을 관리하는 메서드와 폼에서 발생 가능한 사건들을 처리하는 이벤트 제공

 8월 20일 <WindowsForm 버튼어 메시지 박스 출력>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnName_Click(object sender, EventArgs e)
        {            

             MessageBox.Show("안녕하세요 만나서 반갑습니다");

        }
    }
}


 MyWindowsForm 메뉴컨텍스트 연습 frmMain.Cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms
{
    public partial class MainForm : Form
    {
        private int PenWidth = 1;
        private Color InColor = Color.Red;
        enum eShape { CIRCLE, RECT };
        eShape Shape = eShape.CIRCLE;

        public MainForm()
        {
            InitializeComponent();
        }

        private void miExit_Click(object sender, EventArgs e)
        {
            //현재 프로그램기본적인 종료
            Application.Exit();
           
        }
        private void mnuAbout_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("프로그램 정보");
            frmAbout fa = new frmAbout();
            //모달폼 : 현재창을 닫아야지만, 메인으로 이동 가능
            fa.ShowDialog(); //모달대화상자형태로 하고자 할때
        }

        private void btnButton_Click(object sender, EventArgs e)
     

    {
         //모달리스 폼 : 독립적인 하나의 폼
         MyWinForms.Controls.frmButton fb = new MyWinForms.Controls.frmButton();
         fb.MdiParent = this; //MDI 컨테이너를 현재폼(메인)으로 설정 
          fb.Show();
    }

        //2.컨텍스트 메뉴 관련
        private void cmsProgram_Click(object sender, EventArgs e)
        {
            //frmAbout fa = new frmAbout();
            //ShowDialog();
            mnuAbout_Click(null,null); //재사용 호출시 사용

        }
       
        private void cmsExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void mnuShapCircle_Click(object sender, EventArgs e)
        {
            Shape = eShape.CIRCLE;
            Invalidate();
        }

        private void MainForm_Paint(object sender, PaintEventArgs e)
        {
           

  Pen P = new Pen(Color.Black, PenWidth);
             SolidBrush B = new SolidBrush(InColor);

            switch (Shape)
            {
                case eShape.CIRCLE:
                    e.Graphics.FillEllipse(B, 100, 50, 100, 100);
                    e.Graphics.DrawEllipse(P, 100, 50, 100, 100);
                    break;
                case eShape.RECT:
                    e.Graphics.FillEllipse(B, 100, 50, 100, 100);
                    e.Graphics.DrawEllipse(P, 100, 50, 100, 100);

                    break;
            }
        }

        private void mnuShapeRect_Click(object sender, EventArgs e)
        {
            Shape = eShape.RECT;
            Invalidate();
        }

    }
}



 8월 21일 <FrmButtonLabelTextBox.cs>

 MainForm 에서 해야할 이벤트 발생.Cs

  private void btnLavelText_Click(object sender, EventArgs e)
        {
             //컨트롤 에러 발생 (참조할수 없는 에러)
            //MyWinForms.Controls.FrmButtonLabelTextBox blt = new 
            //MyWinForms.Controls.FrmButtonLabelTextBox();
            //blt.MdiParent = this;
            //blt.Show(); // 네임스페이스 선언 후 사용하면 가능
            FrmButtonLabelTextBox frmButton = new FrmButtonLabelTextBox();
            frmButton.Show();
        }

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms
{
    public partial class FrmButtonLabelTextBox : Form
    {
        public FrmButtonLabelTextBox()
        {
            InitializeComponent();
        }

        private void btnCmd_Click(object sender, EventArgs e)
        {
            int kor = Convert.ToInt32(txtKor.Text);
            int eng = Int32.Parse(txtEng.Text);

            int tot = kor + eng;

            MessageBox.Show(string.Format("{0} + {1} = {2}", kor, eng, tot));
 
            btnCancel_Click(null, null); //재 호출
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //클리어 여러가지 방식으로 표현하기 위해
            this.txtKor.Text = "";
            this.txtEng.Text = string.Empty;

            txtKor.Focus(); //포커스 이동

        }

        private void txtKor_KeyDown(object sender, KeyEventArgs e)
        {
           

  //두번째 매개변수 e.keycode로 키보드값을 이벤트 발생
            if (e.KeyCode == Keys.Enter)
            {
                this.txtEng.Focus();                 
            }

        }
        private void txtEng_KeyDown(object sender, KeyEventArgs e)
        {
           
  if (e.KeyCode == Keys.Enter)
            {
                btnCmd_Click(null, null);  //호출 하여 재사용가능
            }

        }
    }
}


 FrmCheckBoxRadioButton.cs

 MainForm 에서 해야할 이벤트 발생.Cs
 

private void 체크박스라디오버튼ToolStripMenuItem_Click(objectsender,EventArgs e)
        {
            MyWinForms.Controls.FrmCheckBoxRadioButton radio = new
            MyWinForms.Controls.FrmCheckBoxRadioButton();

            radio.MdiParent = this; 
            radio.Show();
        }


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmCheckBoxRadioButton : Form
    {
        public FrmCheckBoxRadioButton()
        {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            string msg = "";

 
       
            //관심사항

            if (this.chkseeSharp.Checked)
            {
                msg += this.chkseeSharp.Text + "\r\n"   ;
            }

            if (this.chkAsp.Checked)
            {
                msg += this.chkAsp.Text + "\r\n";
            }

            if (!this.chkSilver.Checked)
            {
                //empty
            }
            else
            {
                msg += this.chkSilver.Text + "\r\n";
            }

 
            //성별
            if (this.OptMan.Checked )
            {
                msg += string.Format("{0}{1}{0}", "\r\n", OptMan.Text );
               
            }
            else
            {
                msg += string.Format("{0}{1}{0}", "\r\n", OptWomen.Text);
            }

            this.txtResult.Text = msg;
           
        }

        //CheckBox Checked속성 초기값을 주려고 할때
        private void FrmCheckBoxRadioButton_Load(object sender, EventArgs e)
        {
            this.OptMan.Checked = true;  //Checked
            this.chkSilver.Checked = true; //Checked
        }
    }
}



 8월24일 텍스박스 주요 속성.CS

Menu연결하기 위해 사용되는 .CS 
 
   private void 텍스트박스주요속성ToolStripMenuItem_Click
                                                     (object sender, EventArgs e)
        {
            MyWinForms.Controls.FrmTextBox TextBox = new              
            MyWinForms.Controls.FrmTextBox();

            TextBox.MdiParent = this;
            TextBox.Show();
        }

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyWinForms.Controls
{
    public partial class FrmTextBox : Form
    {
        public FrmTextBox()
        {
            InitializeComponent();
        }

        private void BtnCmd_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("싱글라인" + txtSinglebox.Text);
            sb.Append("멀티라인" + txtDoubleBox.Text);
            sb.Append(string.Format("패스워드 : {0} ", txtPasswordBox.Text));
            sb.Append("마스크 : " + txtMaskBox.Text);
            sb.AppendFormat("리치 : {0}",  txtRichBox.Text);

            MessageBox.Show(sb.ToString());
        }
    }
}


 8월 24일 프로그램 도움말에서 링크과련 .Cs

   private void lnkAuthor_LinkClicked(object sender, 
                                 LinkLabelLinkClickedEventArgs e)
        {
            string url = "
http://fool8585.tistory.com/";
            System.Diagnostics.Process.Start(url);

            //웹브라우저 이동하면서 notepad실행하고 할때..
            System.Diagnostics.Process.Start("notepad.exe");
                  

        }


 8월 24일 클래스 메시지박스 관련 .CS
            //메시지 박스 주요 모양
            //MSDN 온라인 적극활용
            MessageBox.Show("Test");
            MessageBox.Show("캡션","제목");
            MessageBox.Show("버튼의 종료", "버튼",
                             MessageBoxButtons.OKCancel);
            MessageBox.Show("아이콘의 종류",
            "아이콘",MessageBoxButtons.OK ,MessageBoxIcon.Exclamation);

 8월 24일 콤보박스와 리스트박스 .Cs
          //동적으로 아이콘의 종류를 리스트박스에 초기화
            //lstIconBox.Items.Add("안녕하세요");
            //lstIconBox.Items.Add("반값습니다");
            lstIconBox.Items.Add(MessageBoxIcon.Error.ToString());
            lstIconBox.Items.Add(MessageBoxIcon.Information.ToString());
            lstIconBox.Items.Add(MessageBoxIcon.Stop.ToString());
            lstIconBox.Items.Add(MessageBoxIcon.Question.ToString());
            lstIconBox.Items.Add(MessageBoxIcon.Warning.ToString());
            lstIconBox.Items.Add(MessageBoxIcon.Hand.ToString());
확인버튼 눌렀을경우 발생할 이벤트 .CS

private void btnCmd_Click(object sender, EventArgs e)
        {
            if (lstIconBox.SelectedIndex != -1 && lstIconBox.SelectedIndex !=
                                                    -1)
            {
                string btn = lstIconBox.Items[lstIconBox.SelectedIndex].
                                ToString();
                string icon = lstIconBox.Items
                                  [lstIconBox.SelectedIndex].ToString();

                //process
                MessageBox.Show(
                    string.Format("버튼 : {0}, 아이콘 {1}", btn, icon));
            }
            else
            {
                MessageBox.Show("콤보박스와 리스트박스를 선택해주세요 ");
            }
        }

 Main Menu 관련 이벤트 발생
MyWinForms.Controls.FrmComboListBox ComboList = new MyWinForms.Controls.FrmComboListBox();
            ComboList.MdiParent = this;
            ComboList.Show();

 8월 24일 ...콤보박스와 리스트박스 IF  ~else if 사용

 if (lstIconBox.SelectedIndex != -1 && lstIconBox.SelectedIndex != -1)
            {
                string btn = lstIconBox.Items
                                [lstIconBox.SelectedIndex].ToString();
                string icon = lstIconBox.Items
                                [lstIconBox.SelectedIndex].ToString();

                //process
                MessageBox.Show(
                    string.Format("버튼 : {0}, 아이콘 {1}", btn, icon));
            }
            else
            {
                DialogResult result = MessageBox.Show
                                          ("콤보박스와 리스트박스를 선택해주세요 
                                          ","Caption",MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    txtMessageBox.Text = "확인 클릭";
                }
                else if (result == DialogResult.Cancel)
                {
                    txtMessageBox.Text = "최소 버튼";
                }
            }


 8월 24일 GroupBox관련 .CS
 groupBox1.Dock = DockStyle.Right;
 groupBox2.Dock = DockStyle.Top;
 <Dock관련 속성>
 하나의 컨트롤이 해당 컨테이너의 가장자리에 도킹되면 이 컨트롤은 컨테이너의 크기가 바뀔 때 항상 가장자리에 대한 플러시에 놓이게 됩니다.
둘 이상의 컨트롤이 가장자리에 도킹되면 컨트롤은 해당 Z 순서에 따라 나란히 표시되며 Z 순서 이상의 컨트롤은 컨테이너의 가장자리에서 떨어진 곳에 놓이게 됩니다.
 멤버이름 설명 
 None  컨트롤이 도킹 되지 않습니다
 Top  컨트롤이 위쪽에 도킹 됩니다 
 Bottom  컨트롤이 아래쪽에 도킹 됩니다
 Right  컨트롤이 오른쪽에 도킹 됩니다
 Left  컨트롤이 왼쪽에 도킹 됩니다
 Fill  컨트롤이 가장장리에 도킹되며 알맞게 조절






반응형

'.Net Project > .Net C#' 카테고리의 다른 글

인터넷쇼핑몰구축(Console)  (0) 2009.08.21
103장 체중관리 프로그램(Console)  (0) 2009.08.21
101장 프로젝션  (0) 2009.08.20
100장 쿼리표현식(LINQ)  (0) 2009.08.19
99장 람다식  (0) 2009.08.19
posted by Magic_kit
2009. 8. 20. 11:18 .Net Project/.Net C#
반응형

프로젝션 ?
select절은 출력 대상을 지정하는데 순회 변수를 적어 데이터 소스의 값을 그대로 출력

select절을 변경하면 출력 형태를 바꿀 수 있는데 이처럼 결과셋의 출력 형태를 데이터 소스와는 다르게 변형하는 것을 프로젝션이라고 한다. 

Projection.Cs

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

namespace 프로젝션
{
    class Program
    {
        public class Product
        {
            public string Name { get; set; }
            public int Quantity { get; set; }

        }
        public class ProName
        {
            public string ModelName { get; set; }
        }
        static void Main(string[] args)
        {
            int[] data = { 3, 4, 5, 2, 1 };

             //기본형태,배열형태
            IEnumerable<int> q = from d in data where d % 2 == 0 select d;
            int[] even = (from d in data where d % 2 == 0 select d).ToArray(); 
            
            //리스트               
           List<int> lst = (from d in data where d % 2 == 0 select d).ToList();            

  Product[] Products = {
                                    new Product {Name="닷넷", Quantity=1000},
                                    new Product{Name="닷넷", Quantity=1000}
                               };

            var pro = from p in Products select new Product
                         { Name = p.Name, Quantity = p.Quantity };
           
            foreach (var item in pro)
            {
                Console.WriteLine("{0} {1}", item.Name, item.Quantity);
            }
        }
    }
}

반응형

'.Net Project > .Net C#' 카테고리의 다른 글

103장 체중관리 프로그램(Console)  (0) 2009.08.21
102장 윈폼(Windows Form)  (0) 2009.08.20
100장 쿼리표현식(LINQ)  (0) 2009.08.19
99장 람다식  (0) 2009.08.19
97장 초기화자(Initilizer)  (0) 2009.08.18
posted by Magic_kit
2009. 8. 19. 13:53 .Net Project/.Net C#
반응형

 LINK(Language INtegrated Query)
닷넷 프로엠워크 3.5에서 새로 도입된 방식으로서, 데이터를 다루는 획기적인 방법입니다.

게임이나 시스템 소프트웨어 같은 일부 특수한 경우를 제외하고 대부분 응용 프로그램들은 데이터가 있어만 동작이 가능하며, 데이터를 읽고 검색하는 일은 반드시 아주 높으며 중요한 작업 입니다.

쿼리란.. 데이터 소스에서 특정 조건에 맞는 데이터를 검색하는 지시사항입니다.
명령을 내리면 서버나 DB 모듈이 쿼리의 지시대로 데이터를 구해 리턴을 하며, 데터를 있는 
그대로 일기만 하는 것이 아니라, 보기 좋게 정렬하거나 그룹핑을 할 수도 있어 출력방식에 대한 
지시까지도 포함 하고 있습니다. 

 IEnumerable Interface.cs

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

public class IEnumerable인터페이스
{
    public static void Main()
    {
        //link
        int[] data = { 3, 5, 4, 2, 1 };

        //IEnumerable 인터페이스 변수 선언/초기화
        //System.Collections.Generic.IEnumerable<int> query = from d in data
        //                                                    where d % 2 == 0
        //                                                    select d;

        //일종의 공식이라고 생각하며 쿼리문 잘 활용 DB연결시 장점을 가지고 있음

       

IEnumerable<int> query = from d in data where d % 2 == 0 select d; 

        foreach (var item in query)
        {
            //data라는 배열에서 짝수인것만 뽑아내고 있다.
            Console.WriteLine("{0}",item);
        }

    }
}

 쿼리연산자.cs
쿼리연산자란 ?
가장 직접적인 확장이 가능한것을 의미하며, 쿼리 표현식은 구하고자 하는 데이터와 출력방식을 함축적으로 설명하는 일종의 스크립트 언어로써, 사용되고 있습니다.

form으로 시작해서 select나 group라고 할 수 있으며, 조건없이 모든 데이터를 읽어 
출력하고 있으며, 배열을 정의하고 이 배열을 데이터 소스로 사용 가능 합니다.

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

 public class Product //속성을 지정하기 위해 생성
{
    public string Name { get; set; } //상품명
    public int UnitPrice { get; set; } //단가
}

public class 쿼리식
{
    public static void Main()
    {
        //1.원본 데이터 : Product형 배열
        Product[] pros = { new Product { Name = "닷넷", UnitPrice = 1000 },
                                new Product { Name = "자바", UnitPrice = 1000 } };

        //object타입으로 배열선언 
       

 object[] arr = { 10, 20, 30 };

        //2.쿼리식 Link으로 뽑아내기 
        

 IEnumerable<Product> q = from p in pros where p.Name[0] =='닷'
                                            select p;

        //IEnumerable<Product> q = from p in pros select p; //모두 출력

  IEnumerable<int> query = from int a in arr where a % 4 == 0
                                             select a; //4의 배수 추출 

        //IEnumerable<int> query = from int s in arr select s;  //모두출력
       
       
//3.출력
    foreach (var item in q)
        {
            Console.WriteLine("{0}, {1}", item.Name, item.UnitPrice);
           
        }

        //object타입선언후 출력하기위해 사용
   foreach (var item in query)
        {
            Console.WriteLine("{0}",item);
        }
      
}
}

 표준쿼리연산자.cs
 VB9.0dms LINQ 지원을 위해 언어 자체에 쿼리 표현식이라는 기능을 추가

쿼리 구현을 위한 메서드를 메서드 쿼리 처리자(Standard Query Operators)라고
부르고 있으며, 직역하여 말하자면 표준 쿼리 연산자라고 불러야 겠습니다 (+,-) 같은 연산자처럼 셈을 하는 것이 아니라 좀 더 복잡한 처리를 수행할 수 있는 메서드 이므로,
처리자로 변역을 하고 있습니다.

또한 쿼리 표현식은 사용중인 메서드는 대신하여 바로 호출할 수도 있으며,
메서드보다는 쿼리 표현식이 더 간결하고 가독성도 높으므로 가급적이면 쿼리 표현식을
쓰기를 권하고 있습니다.

단점으로는 모든 쿼리를 다 표현하지 못하고 있는다는것에 한계가 존재하고 있으며,
지원하지 못하는 동작들은 직접호출해야 한다는 단점을 가지고 있습니다.

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

public class 표준쿼리연산자
{
    public static bool EvenNum(int x) { return (x % 2 == 0); }
    public static void Main()
    {

        //input
        int[] data = { 3, 5, 4, 2, 1 };
        //process
      
   
     //IEnumerable<int> q = from d in data select d; //전체출력
        //IEnumerable<int> q = from d in data where d % 2 == 0 select d;
        //짝수/ 1.쿼리식
        //IEnumerable<int> q = from d in data where d % 2 == 0 orderby d
  
                                     
select d; //정렬
       
        //var q = data.Where(EvenNum);
//2.메서드를 통해서 짝수일때만 반환
       

  var q = data.Where(delegate(int x) { return(x%2 ==0);}); //익명메서드       



        //output

        foreach (var item in q)
        {
            Console.WriteLine("{0}",item);
        }
}
}

 쿼리식 반환값 처리.Cs
 쿼리식 반환값 처리
아래와 같은 내용으로 반환값을 처리 (form d ~ select d).ToList()
List<int> lst = (from d in data orderby d descending select d).ToList(); 

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

public class 쿼리식반환값처리
{
    public static void Main()
    {
        int[] data = { 3, 5, 4, 2, 1 };

        //Process
    

     IEnumerable<int> q = from d in data select d; //기본
        var query = from d in data select d; //var   
  
 int[] sorted = (from d in data orderby d select d).ToArray(); //배열
        
        for (int i = 0; i < sorted.Length; i++)
        {
            Console.WriteLine("{0}", sorted[i]);
        }
    
     //컬렉션
List<int> lst = (from d in data orderby d descending select d).ToList(); 

        for (int i = 0; i < lst.Count; i++)
        {
            Console.WriteLine("{0}", lst[i]);
           
        }
    }
}

 지연된 실행.Cs
 지연된실행이란?
쿼리는 단일값을 구하는 간단한 질문일 수도 있지만, 때로는 거대한 데이터 집합을
요구하는 것일 수도 있으며, 내용에 따라 오랜시간이 걸릴 수 도 있기 때문에 LINQ는
쿼리를 즉시 실행하지 않고 아래의 내용과 같이 3단계를 거쳐 구성하고 있습니다.
 1. 원하는 데이터가 저장된 데이터 소스 준비
    배열이나 컬렉션 정도는 소스에서 간단히 정의 할 수 있지만, DB나 XML문서는
    다소 복잡한 과정을 통하여 연결 또는 파싱해 두어야  합니다.
 2. 질문 내용에 따라 쿼리가 생성되며,  어떤 조건에 맞는 데이터를 가져 오라거나
    가져온 데이터를 어떤식으로 출력하라는 명령문 작성
 3. 생성된 쿼리 실행 foreach문 또는 for 통하여 실행


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

public class 지연된실행
{
    public static void Main()
    {
        int[] data = { 3, 5, 4, 2, 1 };
        

 var q = from d in data orderby d select d;

        //for (int i = 0; i < data.Length; i++)
        //{
        //    Console.WriteLine("{0}",data[i]);
           
        //}
        foreach (var item in q)
        {
            Console.WriteLine("{0}",item);
           
        }

        //중간에 데이터 변경 

   data[0] = 1000;
        foreach (var item in q)
        {
            Console.WriteLine("{0}",item);
        }

      
}
}

 쿼리 표현 (알고리즘) 활용.Cs

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

public class 합계카운트평균
{
    public static void Main()
    {
        //input
        int[] data = { 3, 5, 4, 2, 1 };
        //process
        //var q = from d in data where d % 2 == 0 select d;

        var q = from d in data select d; //모두출력

        int sum = q.Sum(); //합계
        int cnt = q.Count(); //카운터
        int avg = sum / cnt;//평균
        //평균 Convert이용하여 표현 가능
        int avgg = Convert.ToInt32(q.Average()); //평균

        //다른방식 최소값 구하기(방식무수히~)
        //최대값

        int min = (from d in data select d).OrderByDescending(p => p).First();
        //최소값
        int listmin = (from d in data select d).OrderByDescending(p => 
                                                          p).Last();
        //최소값
        int minn = (from d in data select d).OrderBy(p => p).First();

        //output
        Console.WriteLine("합계 : {0} \n카운트 : {1} \n평균 : {2}", sum,
                                         cnt, avg);
        Console.WriteLine("평균 : {0}",avgg);
   
        //최대값(코드간결장점)
        Console.WriteLine("최대값 :{0}",(from d in data select d).Max());
       
        //최소값
        Console.WriteLine("최소값 :{0}", min);
        Console.WriteLine("최소값:{0}",listmin);
        Console.WriteLine("최소값 :{0}", minn);
    }
}


 쿼리 표현 (알고리즘) 병합 활용.Cs

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

public class 병합
{
    public static void Main()
    {
        int[] data1 = { 3, 5, 4 };
        int[] data2 = { 2, 1 };

        //Union사용 결합후 orderBy정렬

 int[] result = (from o in data1 select o).Union(from t in data2
                           select t).OrderBy(x => x).ToArray();
        
        for (int i = 0; i < result.Length; i++)
        {
            Console.WriteLine("{0}", result[i]);
           
        }

    }
}


 쿼리 표현 (알고리즘) 그룹 알고리즘.Cs

using System;
using System.Collections.Generic;
using System.Collections;
using System.LINQ //완전조아~ 넌 이제 내꼬얌 !!
namespace LINQ
{
    using System.Linq;

    public class ProductInfo
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
    }

    public class 그룹알고리즘
    {
        public static void Main()
         {
            //input

  List<ProductInfo> lst = new List<ProductInfo>()
             {
                 new ProductInfo{Name="Radio", Quantity=3},
                 new ProductInfo{Name="TV", Quantity=1},
                 new ProductInfo{Name="Radio", Quantity=2},
                 new ProductInfo{Name="DVD", Quantity=5},
             };
            
            //process
 IEnumerable<IGrouping<string, ProductInfo>>
                               q = from p in lst group p by p.Name;
             
            //Output
             foreach (var item in q)
             {
                 //그룹화된 것이 순서대로 출력
                 Console.WriteLine("{0}",item.Key);

                 foreach (var pi in item)
                 {
                     Console.WriteLine("상품 :{0} 판매량:{1}",
                                            pi.Name, pi.Quantity);                    
                 }
             }
         }
    }


쿼리표현식 (참고사항)

 http://msdn.microsoft.com/ko-kr/library/bb397676.aspx


반응형

'.Net Project > .Net C#' 카테고리의 다른 글

102장 윈폼(Windows Form)  (0) 2009.08.20
101장 프로젝션  (0) 2009.08.20
99장 람다식  (0) 2009.08.19
97장 초기화자(Initilizer)  (0) 2009.08.18
96장 그룹(Group) 알고리즘  (0) 2009.08.18
posted by Magic_kit
2009. 8. 19. 12:17 .Net Project/.Net C#
반응형

 

람다 표현식이란 ?
코드를 별도의 메서드 정의 없이 인라인으로 바로 작성할 수있는 방법입니다.
 
인수타입은 생략 할 수 있으며, 생략된 타입은 델이케이드의 타입을 따른다.
본체에 명령문 뿐만 아니라 표현식도 쓸 수 있어 좀 더 짧다 
표현식은 트리로도 변환 할 수 있습니다.

익명 메서드나 람다 표현이나 목적은 둘다 코드를 더욱 짧고 간결하게 작성하는 것을
의미                             람다 표현식 a =>a+1 이런식으로 표현하고 있습니다. 

 Program.cs

//정수 하나를 입력받아서, 그 수를 2배하는 코드
using System;

public class 람다식
{
    public static void Main()
    {
        Console.WriteLine(plus(2)); //1.메서드
        plusHandler ph = delegate(int a) { return (a + a); };
        Console.WriteLine(ph(2));

        //3.(매개변수) => 실행문
        plusHandler labda = a => a + a;
        Console.WriteLine(labda(2));

        //(매개변수 2개 이상일경우 => 실행문
        MinusHandler mh = (x,y) => x-y;
        Console.WriteLine(mh(3,5));
    }

    public static int plus(int a){return (a + a);} // 메서드
   
    public delegate int plusHandler(int a);

람다식 (참고사항)

 http://msdn.microsoft.com/ko-kr/library/bb397687.aspx

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


    public delegate int MinusHandler(int a, int b);
}

반응형

'.Net Project > .Net C#' 카테고리의 다른 글

101장 프로젝션  (0) 2009.08.20
100장 쿼리표현식(LINQ)  (0) 2009.08.19
97장 초기화자(Initilizer)  (0) 2009.08.18
96장 그룹(Group) 알고리즘  (0) 2009.08.18
95장 어트리뷰트(Attribute)  (0) 2009.08.18
posted by Magic_kit
prev 1 2 3 4 5 6 7 ··· 18 next