ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
News
Php Tips
Android Programming
Design Pattern By PHP
C# using Linq น่าใช้จริงๆ
C# Tips & Technique
C# Design Pattern
Linux Quick Tips
Java & JavaScript Tips
Database & SQL
ZengCode Framework Guide
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     การใช้งาน LINQ to SQL ใน C#  (2009-11-04)

การใช้งาน LINQ to SQL  ที่มา www.codetoday.net/default.aspx
LINQ to SQL จะประกอบไปด้วยสามส่วนคือ

Entity Class
Data Context
LINQ Query

เอาละครับเรามาเริ่มเขียนโปรแกรมจัดการกับฐานข้อมูลโดยใช้ LINQ กัน
เปิด Visual Studio 2008 ขึ้น (ถ้าใช้ Visual Studio 2005 จะต้องไป Download Linq มาติดตั้งก่อนนะครับ)
หลังจากเปิดขึ้นมาแล้วไปที่ File->New->Project->Visual c#->Console Application ให้ตั้งชื่อโปรเจคแล้วกด Ok
ฐานข้อมูลผมใช้ Northwind นะครับ


จากนั้นจะเข้าสู่หน้า Program.cs
ซึ่งมีโค้ดถูกสร้างขึ้นมาดังนี้

 

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestLinq1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
 

 

หลังจากนั้นให้ไป Add Reference ก่อนไปที่ชื่อโปรเจค คลิกขวาเลือก Add Reference... ในแถบที่ชื่อว่า .NET ให้เลือก
System.Data.Linq และ System.Xml.Linq
หลังจากนั้นตรงที่ประกาศ using ต่างๆให้เพิ่ม using System.Data.Linq; และ System.Xml.Linq; และ System.Data.Linq.Mapping;
(สำหรับ visual studio 2005 จะต้อง add System.Data.DLinq; , System.Data.Extensions; , System.Query; )

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
[Table(Name = "Customers")]
public class Customer
{
    [Column()]
    public string CustomerID;
    [Column()]
    public string companyname;
    [Column()]
    public string city;
    [Column()]
    public string country;
    public static void Main()
    {
        string constr = "Server =.;Database = northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Customer> customers = db.GetTable<Customer>();
        var q = from c in customers select c; //สร้างคำสั่ง select
        foreach (var t in q)
        {
            Console.WriteLine("{0} {1} {2} {3}", t.CustomerID, t.companyname, t.city, t.country);//แสดงผล
        }
        Console.ReadLine();
     }
}
 
 

 

คำอธิบาย
ตรง [Table(Name = "Customers")]  Table เป็น Attribute ซึ่งมี property คือ Name โดย Name นี้ใช้กำหนดชื่อของตารางในฐานข้อมูลที่ต้องการเช่น customers ถ้าไม่มี Name เช่น [Table()] ทางโปรแกรมจะไปใช้ชื่อของคลาสแทน


[Column()]
public string CustomerID; ตรงคำสั่ง [Column()] จะทำหน้าที่ Mapping ระหว่าง ฟิลด์ที่เรากำหนดด้านล่าง(public string CustomerID) กับ ฟิลด์ที่ชื่อ CustomerID ในฐานข้อมูล

DataContext ทำหน้าที่รับข้อมูลจาก Database ในแต่ละตารางในฐานข้อมูลถูกแสดงด้วย Table ซึ่งสามารถเข้าถึงสมาชิกในแต่ละฟิลด์ในตารางด้วยการใช้ GetTable


การใช้ Where เพื่อกำหนดเงื่อนไขการ Query

using System;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Collections.Generic;
[Table(Name = "Shippers")]//กำหนดตารางชื่อ Shippers
public class Shipper
{
    [Column()]
    public int shipperid;
    [Column()]
    public string companyname;
    [Column()]
    public string phone;
    public static void Main()
    {
        string constr = "Server =(local);Database = Northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Shipper> shippers = db.GetTable<Shipper>();
        var q = from c in shippers where c.companyname == "Federal Shipping" select c;
        foreach (var a in q)
        {
            Console.WriteLine("show  {0}\t{1}\t{2}", a.shipperid, a.companyname, a.phone);
        }
        Console.ReadLine();
    }
}


ผลลัพธ์แสดงดังรูป


 

ในการแสดงผลส่วน
 foreach (var a in q)
        {
            Console.WriteLine("show  {0}\t{1}\t{2}", a.shipperid, a.companyname, a.phone);
        }
เราสามารถใช้ชื่อคลาสแทนได้ดังนี้

  foreach (Shipper s in q)
        {
            Console.WriteLine(s.shipperid+"     "+s.companyname+"      "+s.phone);
        }


การใช้ select new

 

using System;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Collections.Generic;
[Table(Name = "Shippers")]//กำหนดตารางชื่อ Shippers
public class Shipper
{
    [Column()]
    public int shipperid;
    [Column()]
    public string companyname;
    [Column()]
    public string phone;
    public static void Main()
    {
        string constr = "Server =(local);Database = Northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Shipper> shippers = db.GetTable<Shipper>();
        var d = from c in shippers where c.companyname == "Federal Shipping" select new { c.phone, c.shipperid };
        foreach (var g in d)
        {
            Console.WriteLine(g.phone+"      "+g.shipperid);
        }
        Console.ReadLine();
    }
}
 

 

LINQ

LINQ มี 5 แบบคือ

LINQ to Object
LINQ to XML
LINQ to DataSet
LINQ to SQL
LINQ to Entities

 Query Operator ใน LINQ มีหลายชนิดเช่น Select,Where,Join,GroupBy,OrderBy,ThenBy,OrderByDescending,ThenByDescending,Cast,GroupJoin,SelectMany

ตัวอย่างการ ใช้งาน Select เพื่อแสดงข้อมูลในตัวแปร array

using System;
using System.Linq;
public class TestLINQ
{
    public static void Main()
    {
        string[] str = { "one","two","three","four","five" };
        var q = from s in str select s;
        foreach (var a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
one
two
three
four
five

การ ใช้ where เพื่อกำหนดเงื่อนไข

using System;
using System.Linq;
public class TestLINQ
{
    public static void Main()
    {
        string[] str = {"one","two","three","four","five"};
        var q =from s in str where s.Length < 4 select s; //ใช้ where เพื่อกำหนดเงื่อนไขวเพื่อให้แสดงสมาชิกที่มีความยาวน้อยว่า 4
        foreach (var a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}
 
 
 
 
ผลลัพธ์
one
two
คำอธิบายที่ได้ one และ two เพราะตรงตามเงื่อนไขที่มีความยาวของตัวอักษรน้อยกว่า 4 (where s.Length <4)


การใช้งาน OfType

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "A", "B", "C" };
        IEnumerable<string> i = str.OfType<string>();
        foreach (string n in i)
        {
            Console.WriteLine(n);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
A
B
C

การใช้งาน OrderBy


using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = from s in str where s.Length == 3 orderby s select s;
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}


ผลลัพธ์จะได้
One
Six
Two
ในตัวอย่างนี้จะเป็นการเลือก สมาชิกในตัวแปร str ที่มีขนาดความยาวตัวอักษรเท่ากับ 3 โดยเรียงลำดับตัวอักษรจาก (a-z)


ตัวอย่างการใช้ where เพื่อเลือกข้อมูลที่มีขนาดความยาวตัวอักษรเท่ากับ 3

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = str.Where(s => s.Length == 3);
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}
 
 
 
ผลลัพธ์จะได้

Two
Six
One


การแสดงข้อความตามเงื่อนไขที่กำหนด

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = str.Where(s => s[0] == 'T');
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
Two
Three
คำอธิบายในตัวอย่างนี้ได้มีเงื่อนไขคือ where(s=>s[0] =='T') หมายถึง ให้เลือกสมาชิกที่ขึ้นต้นด้วยตัวอักษร T ซึ่งในสมาชิกของตัวแปร str จะมีสมาชิกที่ขึ้นต้นด้วยตัว T มี สองสมาชิกคือ Two,Three

 


การใช้งาน  Group

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "Ant", "Hourse", "Zebra", "Bird", "Dog" };
        var q = from s in str orderby s group s by s.Length into mygroups orderby mygroups.Key  select new {Animal = mygroups };
        foreach (var a in q)
        {
            foreach (string s in a.Animal)
            {
                Console.WriteLine(s);
            }
        }
      
        Console.ReadLine();
    }
}

 

การใช้ SelectMany

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "1 A B C","2 D E F","3 G H T"};
        var q = str.SelectMany(s => s.Split(' '));
        foreach (string a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}


ตัวอย่างการแสดงชนิดของสมาชิกใน array

using System;
using System.Linq;
public class TestLamda
{
    public static void Main()
    {
        object[] obj = { 1, "A", 2, "B", 3, "C" };
        var q = obj.Select(o => o.GetType().Name).OrderBy(o => o);
        foreach (object o in q)
        {
            Console.WriteLine(o);
        }
        Console.ReadLine();
    }
}


LINQ to XML

ตัวอย่าง

using System;
using System.Linq;
using System.Xml.Linq;
public class TestLINQ
{
    public static void Main()
    {
        var animals = new[] { new { Name = "puppy", Color = "Brown" }, new { Name = "doppy", Color = "White" }, new { Name = "bamby", Color = "Black" } };
        XElement x = new XElement("animals", from a in animals select new XElement("animal", new XAttribute("Name", a.Name), new XAttribute("Color", a.Color)));
        Console.WriteLine(x);
        Console.ReadLine();
     }
}

 


Comment
Name
Comment
Security CodeCAPTCHA Image

easy tracking
avis car rental discount code

This page took 0.050880 seconds to load.