C# Convert Genaric to dataTable

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jataz2
PHP Super Member
PHP Super Member
โพสต์: 275
ลงทะเบียนเมื่อ: 22/02/2011 11:48 am

C# Convert Genaric to dataTable

โพสต์ที่ยังไม่ได้อ่าน โดย jataz2 »

คาดว่า หลายๆคนคง ถนัดที่จะจัดการข้อมูลใน datatable มากกว่า Generic
เพื่อนลองใช้ code นี้ไปเเปลง generic เป็น datatable ได้ครับ

โค้ด: เลือกทั้งหมด

using System.Collections.Generic;

public partial class UcReport : System.Web.UI.UserControl
{
     private List<InputPerdium> listPerdium = null;

     protected void Page_Load(object sender, EventArgs e)
     {
       LoadGridview();
     }
  
    private void LoadGridview()
    {
        try
        {
            listPerdium = blgInputPD.GetAllItemInputdium();

            if (listPerdium.Count >= 1)
            {
                DataTable dtPD = [color=#FF0000]IEnumerableExt.GenericToDataTable(listPerdium);[/color]
 
                // Let's enjoy it :-)
             }
        }
   }
}


public static class IEnumerableExt
{
    public static DataTable GenericToDataTable<T>(this IEnumerable<T> things) where T : class
    {
        DataTable tbl = new System.Data.DataTable();
        bool buildColumns = false;
        foreach (var item in things)
        {
            Type t = item.GetType();
            var properties = t.GetProperties();
            if (!buildColumns)
            {
                foreach (var prop in properties)
                {
                    Type ptype = prop.PropertyType;
                    if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        ptype = Nullable.GetUnderlyingType(prop.PropertyType.UnderlyingSystemType);
                    }
                    DataColumn col = new DataColumn(prop.Name, ptype);
                    tbl.Columns.Add(col);
                }
                buildColumns = true;
            }
            DataRow row = tbl.NewRow();

            foreach (var prop in properties)
            {
                if (prop.GetValue(item, null) == null)
                {
                    row[prop.Name] = DBNull.Value;
                }
                else
                {
                    row[prop.Name] = prop.GetValue(item, null);
                }
            }

            tbl.Rows.Add(row);
        }

        return tbl;
    }
}
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 89