LINQ to DataSet
.NET프로그래밍/ADO.NET 2009. 9. 30. 16:25 |
* "윈폼"에서 '새 프로젝트 만들기'로 프로젝트 실행
==> Form1.cs [디자인]
-------------------------------------------------------------------------------------
==> Form1.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;
using System.Data.SqlClient;
namespace WinLinqToDataSet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
"server=.;database=AddressBook;uid=AddressBook;pwd=6750440;");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * From AddressBook";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "AddressBook");
// LINQ to DataSet
// LINQ를 사용해서 listBox에 아이템을 추가해보자... DataReader로 해도됨.
var q = ds.Tables[0].AsEnumerable(); // DataTable을 LINQ 타입으로
var addr = from ad in q
orderby ad.Field<string>("Name") // 이름 오름차순
select ad;
foreach (var item in addr)
{
listBox1.Items.Add(item.ItemArray[1] + ", " + item.ItemArray[2]);
}
// DataSet을 반복 ==> 기존방법(위의 LINQ to DataSet코드와 비교해볼것. 결과는 동일함.)
DataTable dt = new DataTable();
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
listBox2.Items.Add(dt.Rows[i]["Name"] + ", " + dt.Rows[i]["Mobile"]);
}
// DataReader로 출력 ==> 위의 2가지 방법과 결과는 동일함. 비교해볼것.
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) // 있는만큼 반복
{
string s = dr["Name"].ToString() + ", " + dr.GetString(2);
listBox3.Items.Add(s);
}
dr.Close();
con.Close();
}
}
}
// DataTableExtensions..::.AsEnumerable 메서드 - IEnumerable<(Of <(T>)>) 개체를 반환하며, 제네릭 매개 변수 T는 DataRow입니다. 이 개체는 LINQ 식 또는 메서드 쿼리에 사용될 수 있습니다.
-------------------------------------------------------------------------------------
[실행결과]
--> "폼(Form1)"에서 "listBox" 3개를 만들어서 "Form1.cs 소스"에서 각각 다른 방법으로 코드를 3번 작성하여, 3개의 "listBox"에 모두 같은 결과를 출력해보았다.
'.NET프로그래밍 > ADO.NET' 카테고리의 다른 글
ToDoList 프로그램(작업 목록) 만들기 (0) | 2009.10.01 |
---|---|
LINQ to SQL (0) | 2009.09.30 |
WinBinding(SqlDataAdapter클래스 내용에서 보충) (0) | 2009.09.30 |
(교재실습) WinCommandBuilder(SqlCommandBuilder 클래스) (0) | 2009.09.30 |
(교재실습) (DataAdapter 연습) (0) | 2009.09.30 |