Visual Basic Language Features (VS2010 [.NET 4]) IN DEPTH

  • 0 ตอบ
  • 4077 อ่าน


  • Newbie
  • *
  • 15
  • 1
    • ดูรายละเอียด
Visual Basic Language Features (VS2010 [.NET 4]) IN DEPTH
« เมื่อ: 24 มิถุนายน 2013, 07:07:56 PM »
1. Dynamic Language Runtime

โค๊ด: [Select]
Imports System.Net
Imports System.Dynamic
Imports System.Runtime.InteropServices
Imports System.Web.Script.Serialization

Public Class DynamicObject2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim lstEpdObj As New List(Of ExpandoObject)
        Dim DynColumns As Integer = 4 'Create Dynamic 4 Columns

        For r As Integer = 0 To 10 'Create Dynamic 10 Rows
            Dim epdObj As New ExpandoObject()
            Dim p = TryCast(epdObj, IDictionary(Of String, Object))
            For c As Integer = 0 To DynColumns - 1
                p("dynColumn" & c) = "Value-" & r & c

        Dim p = From c In lstEpdObj.AsEnumerable()
                     Select c

        Dim dt As DataTable = ToDataTable(lstEpdObj)

        GridView1.DataSource = dt
    End Sub

    'Convert Dynamic Object To DataTable
    Public Shared Function ToDataTable(Items As List(Of ExpandoObject)) As DataTable
        Dim list = Items.Cast(Of IDictionary(Of String, Object))() '.ToList()
        If Not list.Any() Then
            Return Nothing
        End If
        Dim dt As New DataTable()
        list.First().Keys.ForEach(Function(x) dt.Columns.Add(x))
        list.ForEach(Sub(a) a.Values.ForEach(Sub(b) dt.Rows.Add(a.Values.ToArray())))
        Return dt
    End Function

    'Convert Dynamic Object To Json
    Public Shared Function ToJson(ByVal expando As ExpandoObject) As String
        Dim serializer As New JavaScriptSerializer()
        Dim json As New StringBuilder()
        Dim keyPairs As New List(Of String)()
        Dim dictionary As IDictionary(Of String, Object) = TryCast(expando, IDictionary(Of String, Object))

        For Each pair As KeyValuePair(Of String, Object) In dictionary
            If TypeOf pair.Value Is ExpandoObject Then
                keyPairs.Add(String.Format("""{0}"": {1}", pair.Key, TryCast(pair.Value, ExpandoObject).ToList()))
                keyPairs.Add(String.Format("""{0}"": {1}", pair.Key, serializer.Serialize(pair.Value)))
            End If

        json.Append(String.Join(",", keyPairs.ToArray()))

        Return json.ToString()
    End Function
End Class

« แก้ไขครั้งสุดท้าย: 24 มิถุนายน 2013, 07:26:56 PM โดย smpksme »