2016년 9월 12일 월요일

[C#학원,닷넷학원추천★탑크리에듀]C# LINQ(링크)Linq To DataSet(데이터셋/데이터테이블과링크)

C# LINQ(링크)Linq To DataSet(데이터셋/데이터테이블과링크)

IEnumerable<T> 제네릭 인터페이스를 구현한 데이터 소스는 LINQ을 통해 쿼리할 수 있으므로
DataSet의 DataTable에 대해 AsEnumerable을 호출하면 LINQ to DataSet 쿼리의 데이터 소스 역할을 하는 제네릭 IEnumerable<T> 인터페이스를 구현한 개체가 반환되므로 Linq 쿼리식에서 이용할 수 있다.

LINQ to DataSet 쿼리 역시 쿼리 식 구문과 메서드 기반 쿼리 구문이라는 두 가지 구문 형식으로 만들 수 있다.

쿼리 식 구문
쿼리 식은 선언적 쿼리 구문으로 이 구문을 사용하면 C#에서 SQL에서와 비슷한 형식으로 쿼리를 작성할 수 있다.

메서드 기반 쿼리 구문
LINQ to DataSet 쿼리를 작성하는 데 메서드 기반 쿼리를 사용할 수도 있다.
메서드 기반 쿼리 구문은 메소드 형태에 람다 식을 매개 변수로 전달하는 방법이다.

using System;
using System.Data;
using System.Collections;
using System.Linq;

class LinqToDataSet
{
    static void Main()
    {
        //CUSTOMER 데이터 생성
        DataTable customer_dt = new DataTable("customer");

        DataColumn col1 = new DataColumn();
        DataColumn col2 = new DataColumn();
        DataColumn col3 = new DataColumn();
        DataColumn col4 = new DataColumn();

        col1.DataType = System.Type.GetType("System.Int16");
        col1.ReadOnly = true; col1.AllowDBNull = false; col1.Unique = true;
        col1.ColumnName = "ID"; col1.AutoIncrement = true; col1.AutoIncrementSeed = 1;

        col2.DataType = System.Type.GetType("System.String");
        col2.ColumnName = "Name";

        col3.DataType = System.Type.GetType("System.String");
        col3.ColumnName = "Addr"; col3.DefaultValue = "서울";

        col4.DataType = System.Type.GetType("System.String");
        col4.ColumnName = "Tel";

        customer_dt.Columns.Add(col1); customer_dt.Columns.Add(col2);
        customer_dt.Columns.Add(col3); customer_dt.Columns.Add(col4);

        DataRow row1 = customer_dt.NewRow();

        row1[1] = "가길동"; row1[2] = "수원"; row1[3] = "111-2222";
        customer_dt.Rows.Add(row1);

        DataRow row2 = customer_dt.NewRow();
        row2[1] = "나길동"; row2[2] = "울산"; row2[3] = "111-2222";
        customer_dt.Rows.Add(row2);

        DataRow row3 = customer_dt.NewRow();
        row3[1] = "다길동"; row3[2] = "부산"; row3[3] = "333-2222";
        customer_dt.Rows.Add(row3);
        Console.Write("\n");

        foreach (DataColumn header in customer_dt.Columns)        {

            Console.Write("{0, -6}\t", header.ColumnName);
        }

        Console.WriteLine("\n---------------------------------");
        foreach (DataRow rows in customer_dt.Rows)
        {
            foreach (DataColumn cols in customer_dt.Columns)
            {
                Console.Write("{0, -4}\t", rows[cols.ColumnName]);
            }
            Console.Write("\n");
        }
        Console.WriteLine("\n"); Console.WriteLine("Done!, Press Enter.");

        DataSet set = new DataSet("customer_sales");
        set.Tables.Add(customer_dt);

        //DataSet의 내용을 XML로 출력
        Console.WriteLine(set.GetXml());

        //--------------------------------
        // 쿼리식 기반 Linq To DataSet
        //--------------------------------
        IEnumerable query = from customer in customer_dt.AsEnumerable()
                            select customer;

        Console.WriteLine("-----------------------------------------");
        Console.WriteLine("Customers : ");
        foreach (DataRow r in query)
        {
            Console.WriteLine(r.Field<string>("Name") + "::" + r.Field<string>("Addr") + "::" + r.Field<string>("Tel"));
        }

        //--------------------------------
        // 쿼리식 기반 Linq To DataSet
        //--------------------------------
        IEnumerable query0 = from customer in customer_dt.AsEnumerable()
                             select customer.Field<string>("Name");

        Console.WriteLine("-----------------------------------------");
        Console.WriteLine("Customer Names : ");
        foreach (string customerName in query0)       
        {
            Console.WriteLine(customerName);
        }

        //--------------------------------------
        // 메소드 기반 쿼리구문 Linq To DataSet
        //--------------------------------------
        var query2 = customer_dt.AsEnumerable().
                        Select(customer => new
                        {
                            Name = customer.Field<string>("Name"),
                            Addr = customer.Field<string>("Addr"),
                            Tel = customer.Field<string>("Tel")
                        });

        Console.WriteLine("-----------------------------------------");
        Console.WriteLine("Customers : ");
        foreach (var customerInfo in query2)
        {
            Console.WriteLine("Name: {0}, Addr: {1}, Tel : {2}",
                customerInfo.Name, customerInfo.Addr, customerInfo.Tel);
        }
        Console.WriteLine("-----------------------------------------");

        //SALES 데이터 생성
        DataTable sales_dt = new DataTable("sales");

        DataColumn scol1 = new DataColumn();
        DataColumn scol2 = new DataColumn();

        scol1.DataType = System.Type.GetType("System.String");
        scol1.ColumnName = "Name";

        scol2.DataType = System.Type.GetType("System.String");
        scol2.ColumnName = "Goods"; 

        sales_dt.Columns.Add(scol1);
        sales_dt.Columns.Add(scol2);

        DataRow srow1 = sales_dt.NewRow();
        srow1[0] = "가길동"; srow1[1] = "수박"; 
        sales_dt.Rows.Add(srow1);

        DataRow srow2 = sales_dt.NewRow();
        srow2[0] = "나길동"; srow2[1] = "참외";
        sales_dt.Rows.Add(srow2);

        set.Tables.Add(sales_dt);  
        //---------------------------------------------

        var query3 =
                    from customer in customer_dt.AsEnumerable()
                    from sales in sales_dt.AsEnumerable()
                    where customer.Field<string>("Name") == sales.Field<string>("Name")
                    select new
                    {
                        Name = customer.Field<string>("Name"),
                        Addr = customer.Field<string>("Addr"),
                        Goods = sales.Field<string>("Goods")
                    };

        foreach (var customerSale in query3)
        {
            Console.WriteLine("Name: {0}, Addr: {1}, Goods : {2} ",
                customerSale.Name, customerSale.Addr, customerSale.Goods);
        }
    }
}

[결과]
ID      Name    Addr    Tel
---------------------------------
1       가길동  수원    111-2222
2       나길동  울산    111-2222
3       다길동  부산    333-2222


Done!, Press Enter.
<customer_sales>
  <customer>
    <ID>1</ID>
    <Name>가길동</Name>
    <Addr>수원</Addr>
    <Tel>111-2222</Tel>
  </customer>
  <customer>
    <ID>2</ID>
    <Name>나길동</Name>
    <Addr>울산</Addr>
    <Tel>111-2222</Tel>
  </customer>
  <customer>
    <ID>3</ID>
    <Name>다길동</Name>
    <Addr>부산</Addr>
    <Tel>333-2222</Tel>
  </customer>
</customer_sales>
-----------------------------------------
Customers :
가길동::수원::111-2222
나길동::울산::111-2222
다길동::부산::333-2222
-----------------------------------------
Customer Names :
가길동
나길동
다길동
-----------------------------------------
Customers :
Name: 가길동, Addr: 수원, Tel : 111-2222
Name: 나길동, Addr: 울산, Tel : 111-2222
Name: 다길동, Addr: 부산, Tel : 333-2222
-----------------------------------------
Name: 가길동, Addr: 수원, Goods : 수박
Name: 나길동, Addr: 울산, Goods : 참외




댓글 없음:

댓글 쓰기