newind2000
2015. 6. 17. 16:34
================================ Outline ====================================
LINQ
LINQ를 활용한 성적처리 프로그램 작성
----------------------------------------------------------------------------
LINQ
LINQ는 Language INtegrated Query의 약자로, C# 언어에 통합된 데이터 질의 기능이다.
데이터를 읽고, 거르고, 정렬하는 작업을 간단하게 처리하도록 도와준다.
기본적으로 데이터를 추출하여 사용할 때는 다음의 질문의 답이 필요하다.
1. from: 어떤 데이터 집합에서 찾을 것인가?
2. where: 어떤 값의 데이터를 찾을 것인가?
3. select: 어떤 항목을 추출할 것인가?
지금까지 학습한 내용으로 짠 코드
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace _20150617_LINQ { class Profile { public string Name { get; set; } public int Height { 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 =172}, new Profile() {Name = "이문세", Height =178}, new Profile() {Name = "하동훈", Height =171} }; List<Profile> profiles = new List<Profile>(); 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); } }
} }
**List에 대한 학습이 필요하다. |

일반적인 쿼리식(Query Expression)은 from절로 시작한다.
from절은 쿼리식의 대상이 될 데이터 원본(Data Source)과 데이터 원본 안에 들어있는 각 요소 데이터를 나타내는 전역 범위 변수를 지정하는 역할이다.
from의 데이터 원본은 색인이 가능한 목록, IEnumerable<T> 인터페이스를 상속하는 형식이어야 한다. 배열 혹은 컬렉션에 입력 가능하여야 한다.
**IEnumerable과 일반화에 대한 학습 필요
where은 필터 역할을 하는 연산자이다. if의 역할을 한다.
oderby는 데이터의 정렬을 수행하는 연산자이다. 오름차순과 내림차순을 따로 지정하지 않으면 오름차순으로 정렬된다.
select는 최종 결과를 추출하는 쿼리식의 마침표 같은 존재이다.
LINQ를 사용하여 위의 코드를 수정해 보자.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
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 [] {99, 80 ,70 ,24}}, new Class(){Name = "분홍반", Score = new int [] {60, 45 ,87 ,72}}, new Class(){Name = "파랑반", Score = new int [] {92, 30 ,85 ,94}}, new Class(){Name = "노랑반", Score = new int [] {90, 88 ,0 ,17}}
}; 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("낙제: {0} ({1})", c.Name, c.Lowest); } } }
|

p/446 이중 from 예제,
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
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 [] {99, 80 ,70 ,24}}, new Class(){Name = "분홍반", Score = new int [] {60, 45 ,87 ,72}}, new Class(){Name = "파랑반", Score = new int [] {92, 30 ,85 ,94}}, new Class(){Name = "노랑반", Score = new int [] {90, 88 ,0 ,17}}
}; 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("낙제: {0} ({1})", c.Name, c.Lowest); } } }
|

LINQ를 활용한 성적처리 프로그램 작성
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections;
namespace ConsoleApplication5 { class Student { string name;
public string Name { get { return name; } set { name = value; } } int math;
public int Math { get { return math; } set { if (value < 0 && value > 100) { math = 0; } math = value; } } int science;
public int Science { get { return science; } set { if (value < 0 && value > 100) { science = 0; } science = value; } } int english;
public int English { get { return english; } set { if (value < 0 && value>100) { english = 0; } english = value; } } int avg;
public int Avg { get { return avg; } set { avg = value; } } public void Show() { Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t", Name, Math, English, Science, (english + math + science), (english + math + science) / 3); } } class Program { static void Main(string[] args) { string name; Student std; ArrayList arr = new ArrayList(); while (true) { Console.Write("이름을입력하세요..하기싫으면 q : "); name=Console.ReadLine(); if(name=="q") { break; } std = new Student(); std.Name = name; Console.Write("수학점수 : "); std.Math = int.Parse(Console.ReadLine()); Console.Write("영어점수 : "); std.English = int.Parse(Console.ReadLine()); Console.Write("과학점수 : "); std.Science = int.Parse(Console.ReadLine()); std.Avg = (std.Math + std.English + std.Science) / 3; arr.Add(std); Console.WriteLine("입력이완료되었음!!"); } Console.WriteLine("출력"); Console.WriteLine(" 이름 수학 영어 과학 총점 평균 순위");
var query = from Student student in arr orderby student.Avg descending select student; int c = 1; foreach (Student s in query) { s.Show(); Console.WriteLine(c); c++; }
Console.ReadLine(); } } }
|