Wednesday, 12 February 2014

.Net Tips : Convert DataTable object to list of class object using LINQ with C#.Net and VB.Net example

You can fill List of object from DataTable using LINQ. There are many situations where you need to get data from DB into data table and after that from data table to proper class object. We can do this easily with LINQ.

Here is example for this.
In this example we take one DataTable object which contains two columns 'product_id' and 'product_name'. This DataTable has many rows. Now we want to convert DataTable object into list of class object. We have one Class 'clsProduct' which has two property 'product_id' and 'product_name'. Now we transform DataTable object data in to list of clsProduct class object using LINQ.


C#. Net Example :
    private DataTable GetProducts()
    {
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;

        dt.TableName = "product";

        dc = new DataColumn("product_id", int.MaxValue.GetType());
        dt.Columns.Add(dc);

        dc = new DataColumn("product_name");
        dt.Columns.Add(dc);

        dr = dt.NewRow();
        dr["product_id"] = 1;
        dr["product_name"] = "Monitor";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 2;
        dr["product_name"] = "Mouse";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 3;
        dr["product_name"] = "KeyBoard";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 4;
        dr["product_name"] = "LCD";
        dt.Rows.Add(dr);

        return dt;
    }
    public class clsProduct
    {
        public int product_id;
        public string product_name;
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        DataTable dt = GetProducts();
        List<clsProduct> lstProduct;
        lstProduct = (
                        from m in dt.Rows.Cast<DataRow>() 
                        select new clsProduct { 
                            product_id = m.Field<Int32>("product_id"), 
                            product_name = m.Field<string>("product_name") }
                    ).ToList();
    }

VB.Net Examples :
    Private Function GetProducts() As DataTable
        Dim dt As New DataTable()
        Dim dc As DataColumn
        Dim dr As DataRow

        dt.TableName = "product"

        dc = New DataColumn("product_id", Integer.MaxValue.[GetType]())
        dt.Columns.Add(dc)

        dc = New DataColumn("product_name")
        dt.Columns.Add(dc)

        dr = dt.NewRow()
        dr("product_id") = 1
        dr("product_name") = "Monitor"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 2
        dr("product_name") = "Mouse"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 3
        dr("product_name") = "KeyBoard"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 4
        dr("product_name") = "LCD"
        dt.Rows.Add(dr)

        Return dt
    End Function
    Public Class clsProduct
        Public product_id As Integer
        Public product_name As String
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dt As DataTable = GetProducts()
        Dim lstProduct As List(Of clsProduct)
        lstProduct = (
                        From m In dt.Rows.Cast(Of DataRow)()
                        Select New clsProduct With { _
                            .product_id = m.Field(Of Int32)("product_id"), _
                            .product_name = m.Field(Of String)("product_name") _
                    }).ToList()
    End Sub

Output : 
Conversion from DataTable object to Class Object


Below are the books that you would like :

17 comments:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training and placement in chennai | best dot net training in chennai

    ReplyDelete
    Replies
    1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Dot Net Training in Chennai. or learn thru ASP.NET Online Training . Nowadays Dot Net has tons of job opportunities on various vertical industry.

      Delete
  2. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai velachery | dot net training institute in velachery

    ReplyDelete
  3. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    Software Testing Training in Chennai

    ReplyDelete
  4. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  5. This blog gives very important info about .Net Thanks for sharing
    Dot Net Online Training Bangalore

    ReplyDelete
  6. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
    python training in chennai | python training in bangalore

    python online training | python training in pune

    python training in chennai | python training in bangalore

    ReplyDelete
  7. Well somehow I got to read lots of articles on your blog. It’s amazing how interesting it is for me to visit you very often.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    java training in chennai | java training in bangalore

    ReplyDelete
  8. You blog post is just completely quality and informative. Many new facts and information which I have not heard about before. Keep sharing more blog posts.

    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar
    selenium training in chennai

    ReplyDelete
  9. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa training in Chennai

    rpa training in anna nagar | rpa training in marathahalli

    rpa training in btm | rpa training in kalyan nagar

    rpa training in electronic city | rpa training in chennai

    rpa online training | selenium training in training

    ReplyDelete
  10. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    python training in pune
    python training institute in chennai
    python training in Bangalore

    ReplyDelete
  11. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    DevOps online Training

    ReplyDelete
  12. Hi there I am so thrilled I found your website, I really found you by mistake, while I was browsing on Yahoo for something else
    iosh course in chennai

    ReplyDelete
  13. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  14. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Microsoft Azure online training
    Selenium online training
    Java online training
    uipath online training
    Python online training

    ReplyDelete