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 :

38 comments:

  1. 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
  2. This blog gives very important info about .Net Thanks for sharing
    Dot Net Online Training Bangalore

    ReplyDelete
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

    sap hybris training in bangalore

    sap scm training in bangalore

    sap pm training in bangalore

    sap crm training in bangalore

    sap ewm training in bangalore

    ReplyDelete
  9. Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.

    data science course

    ReplyDelete
  10. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.

    ReplyDelete
  11. Glad to chat your blog,I seem to be forward to more reliable articles and i think we all wish to thank so many good articles,blog to share with us.data scientist courses

    ReplyDelete
  12. Thank you for posting informative insights, I think we have got some more information to share with! Do check out
    oracle training in chennai and let us know your thoughts. Let’s have great learning!

    ReplyDelete
  13. This post is very simple to read and appreciate without leaving any details out. Great work!
    data scientist course in hyderabad

    ReplyDelete
  14. Learn Amazon Web Services for excellent job opportunities from Infycle Technologies, the best AWS training center in Chennai. Infycle Technologies gives the most trustworthy AWS course in Chennai, with full hands-on practical training from professional trainers in the field. Along with that, the placement interviews will be arranged for the candidates, so that, they can meet the job interviews without missing them. To transform your career to the next level, call 7502633633 to Infycle Technologies and grab a free demo to know more

    TOP AWS TRAINING IN CHENNAI

    ReplyDelete
  15. Your amazing insightful information entails much to me and especially to my peers. Thanks a ton; from all of us.
    data scientist training and placement

    ReplyDelete
  16. Your article increases the curiosity to learn more about this topic. Keep sharing your information regularly for future reference.
    DevOps Training in Hyderabad
    DevOps Course in Hyderabad

    ReplyDelete
  17. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. cloud computing course in nagpur

    ReplyDelete
  18. AI Patasala is the most rumoured Python Training in Hyderabad developed to help you advance your career with a massive increase in the latest technology.
    Python Training in Hyderabad

    ReplyDelete
  19. I am overwhelmed by your post with such a nice topic. Usually I visit your blogs and get updated through the information you include but today’s blog would be the most appreciable. Well done!
    cloud computing course in hyderabad

    ReplyDelete
  20. Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people..
    ethical hacking training in hyderabad

    ReplyDelete
  21. Your blog provided us with valuable information to work with. Each & every tip of your post is awesome. Thanks a lot for sharing. Keep blogging,
    data science training institute in hyderabad


    ReplyDelete
  22. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.data science course in bhubaneswar

    ReplyDelete
  23. Informative blog and knowledgeable content. Thanks for sharing this awesome blog with us. If you want to learn data science then follow the below link.
    Data Science Training in Hyderabad

    ReplyDelete
  24. You actually make it look so easy with your performance but I find this matter to be actually something which I think I would never comprehend. It seems too complicated and extremely broad for me. I'm looking forward for your next post, I’ll try to get the hang of it! business analytics course in kanpur

    ReplyDelete
  25. I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one data science course in mysore

    ReplyDelete
  26. Happy to visit your blog, I am by all accounts forward to more solid articles and I figure we as a whole wish to thank such huge numbers of good articles, blog to impart to us.
    data science course in hyderabad

    ReplyDelete
  27. I have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.

    Great information.Thanks for sharing the article
    Data science course in hyderabad
    Data science training in hyderabad

    ReplyDelete
  28. very well explained.very useful.Thanks for the post.
    SQL Course in Pune

    ReplyDelete