-
쿼리의 결과를 새로운 객체 컬렉션으로 저장하는 방법C# 예제 공부일기 2020. 7. 28. 20:30
LINQ 쿼리식의 결과에서 새로운 객체를 만들어 컬렉션으로 저장할 수 있다. 다음의 프로그램은 이름,학번, 성적이 포함된 Student 클래스를 사용하여 시험 점수와 평균, 그리고 각 시험에서 커트라인 이상의 점수를 받은 학생들을 출력합니다.
class Student { public string Name { get; set; } public int Id { get; set; } public List<int> Scores { get; set; } } class Program { static List<Student> students; //정적 리스트 선언 static void Main(string[] args) { students = new List<Student> //정적 리스트 생성, 초기화 { new Student{Name="Pjkim",Id=19001001, Scores = new List<int>{86,90,76}}, new Student{Name="BsKim",Id=19001002, Scores = new List<int>{56,92,93}}, new Student{Name="YsCho",Id= 19001003,Scores=new List<int>{69,85,75}}, new Student{Name="BiKang",Id=19001004,Scores=new List<int>{88,80,57}} }; HighScore(0, 80); //첫번째 과목에서 80점 이상! } private static void HighScore(int exam,int cut) { var highscore = from student in students where student.Scores[exam] > cut //exam번째 시험이 cut가 넘을때. select new { Name = student.Name, Scores = student.Scores[exam] }; //highscore<T>에서 T가 Student형이라 위와같은 형태 가능 Console.WriteLine($"{exam + 1}번째 시험에서 {cut} 이상의 점수를 받은 학생"); foreach(var item in highscore) { Console.WriteLine($"{item.Name,-10},{item.Scores }"); } }
'C# 예제 공부일기' 카테고리의 다른 글
소켓 프로그래밍 (네트워크) #2 (0) 2020.07.29 소켓 프로그래밍 (네트워크) #1 (0) 2020.07.29 LINQ의 결과를 리스트나 배열로 반환 (0) 2020.07.28 LINQ를 이용한 조건 검색과 정렬 (0) 2020.07.28 LINQ의 기초 (0) 2020.07.28