IT/C#
LINQ to DataTable
lI헐헐Il
2012. 9. 15. 13:41
// Bind the System.Windows.Forms.DataGridView object // to the System.Windows.Forms.BindingSource object. dataGridView.DataSource = bindingSource; // Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable orders = ds.Tables["SalesOrderHeader"]; // Query the SalesOrderHeader table for orders placed // after August 8, 2001. IEnumerable<DATAROW> query = from order in orders.AsEnumerable() where order.Field<DATETIME>("OrderDate") > new DateTime(2001, 8, 1) select order; // Create a table from the query. DataTable boundTable = query.CopyToDataTable<DATAROW>(); // Bind the table to a System.Windows.Forms.BindingSource object, // which acts as a proxy for a System.Windows.Forms.DataGridView object. bindingSource.DataSource = boundTable; <P><br />orders.AsEnumerable() <P>order.Field("OrderDate") </P> <P>DataTable boundTable = query.CopyToDataTable();
orders.AsEnumerable()
order.Field("OrderDate")
DataTable boundTable = query.CopyToDataTable();
이부분 주목하자. DataTable에 대한 LINQ는 AsEnumerable() 확장 메소드를 통해 DataTable을 열거가능한 형으로 리턴받는다. LINQ로 쿼리해온 데이터는 CopyToDataTable() 메소드를 통해 DataTable로 변환할 수 있다.
DataSet dsProduct = new DataSet(); DataSet dsProductDescription = new DataSet(); dsProduct = dbClass.SelectDetail("SELECT ProductID, Name, ProductNumber, ListPrice FROM Production.Product"); dsProductDescription = dbClass.SelectDetail("SELECT ProductDescriptionID, Description FROM Production.ProductDescription"); var queryProduct = from order in dsProduct.Tables[0].AsEnumerable() join desc in dsProductDescription.Tables[0].AsEnumerable() on order.Field<INT>("ProductID") equals desc.Field<INT>("ProductDescriptionID") select new { ProductID = order.Field<INT>("ProductID"), Name = order.Field<STRING>("Name"), ProductNumber = order.Field<STRING>("ProductNumber"), ListPrice = order.Field<DECIMAL>("ListPrice"), Description = desc.Field<STRING>("Description") }; foreach (var obj in queryProduct) { Console.WriteLine("{0}, {1}, {2}, {3}, {4}", obj.ProductID, obj.ProductNumber, obj.Name, obj.ListPrice, obj.Description); }
두 개의 IEnumerable<T> 개체를 Join할 수 있다. SQL과 흡사하나 결과를 익명타입으로 받는 점, on 구문 내의 equals등이 다르다.
첨부파일은 MSDN에서 제공하는 C# 101 LINQ Sample이다.