-
linqASP.NET/.NET 프레임워크 2022. 5. 1. 21:48
using System; using System.Linq; namespace test { class Program { static void Main(string[] args) { int[] nums = new int[9] {1, 2, 3, 4, 5, 6, 7, 8, 9}; var numQuery = from num in nums where (num % 3 ) == 0 select num; foreach(int num in numQuery) // 결과 출력 Console.Write(num + " "); } } } // 3 6 9using System; using System.Collections.Generic; using System.Linq; namespace test { public class Student { public string name { get; set; } public int score { get; set; } } class Program { static void Main(string[] args) { List<Student> students = new List<Student> { new Student { name = "zzz", score = 88}, new Student { name = "kim", score = 50}, new Student { name = "han", score = 76 }, new Student { name = "park", score = 45 }, new Student { name = "peter", score = 84 }, new Student { name = "lee", score = 98 } }; var smart = from student in students where student.score >= 60 // 60점이상만 orderby student.name ascending//이름순으로 정렬 select student.name; //이름만 추출 foreach(string studentName in smart) //결과 출력 Console.WriteLine(studentName); } } } // han // lee // peter // zzzLinQ (Language-Integrateds Query)
=> 특정 데이터들에서 Query를 하여 데이터를 빠르고 편리하게 추출하는 방식
=> 기본적으로 람다표현식을 사용하여 간결하고 가독성 좋게 작성 가능하다.
from : 어떤 데이터에서 찾을 것인가
where : 어떤 조건으로 찾을 것인가
order by : 어떤 항목을 기준으로 정렬할 것인가
select : 어떤 항목을 추출할 것인가
[ 예시 ] DataTable에서 Linq를 이용해서 data 추출하기
// DataTable 생성 DataTable dt = new DataTable(); dt.Columns.Add("no", typeof(int)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("age", typeof(int)); dt.Columns.Add("regId", typeof(string)); dt.Columns.Add("regDt", typeof(DataTime)); DataRow row = dt.NewRow(); row["no"] = 1; row["name"] = "Amy"; row["age"] = 20; row["regId"] = "dev@gmail.com"; row["regDt"] = DateTime.Now; dt.Rows.Add(row); // 데이터 한 번에 넣는 방법 dt.Rows.Add(new object[] {2, "Jina", 24, "Jina@gmail.com", DateTime.Now}); dt.Rows.Add(new object[] {3, "John", 30, "John@gmail.com", DateTime.Now}); // DataTable에서 Linq를 이용해 데이터 추출 DataTable dtLinq = new DataTable(); // dt table에 name 컬럼에서 중복제거(Distinct)하고 오름차순으로 테이블 생성 // 내림 차순 : OrderByDescending dtLinq = dt.Tables[0].AsEnumerable() .Select(r => r.Field<string>("name")) .Distinct() .OrderBy(o => o); // no 1번 이후 나이 합계 구하기 decimal intTotalAge = dt.Tables[0].AsEnumerable() .Where(s => s.Field<age>("no") > 1) .Sum(r => Convert.ToInt32(r.Field<decimal>("age")));'ASP.NET > .NET 프레임워크' 카테고리의 다른 글
.net 수명주기 (0) 2022.04.24 Infragistics - Grid 기본 (0) 2022.03.04 List<T> 클래스 (0) 2022.03.02 C# - Linq (0) 2022.02.28 postback, viewstate, runat (0) 2022.02.28