'c#'에 해당되는 글 2건

  1. 2013.05.29 확장메소드 사용하기
  2. 2012.09.15 LINQ to DataTable

확장메소드 사용하기

IT/C# 2013. 5. 29. 09:26
using System.Collections.Generic;

public class ShoppingCart {
     public List Products { get; set; }
}

public static class MyExtensionMethods {
     public static decimal TotalPrices(this ShoppingCart cartParam) {
          decimal total = 0;
          foreach(Product prod in cartParam.Products) {
               total += prod.Price;
          }
          return total;
     }
}

decimal cartTotal = cart.TotalPrices();
// DLL을 참조하는 경우에도 해당 클래스에 메소드를 추가한 것처럼 호출할 수 있다.

현재 클래스와 동일한 네임스페이스에 포함되어 있거나, using문으로 지정된 네임스페이스에 존재해야만 한다.
Posted by lI헐헐Il
,

LINQ to DataTable

IT/C# 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이다.

 

101 LINQ Samples.zip

 

Posted by lI헐헐Il
,