Click here to Skip to main content
12,623,511 members (30,176 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

30.3K views
7 bookmarked
Posted

Convert Linq Query Result To DataTable

, 5 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Sometimes you need the Linq query result as datatable (I need it today)Use this: public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query) { if (query == null) { throw new ArgumentNullException("query"); ...
Sometimes you need the Linq query result as datatable (I need it today)

Use this:

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            IDbCommand cmd = ctx.GetCommand((IQueryable)query);
            System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
            adapter.SelectCommand = (System.Data.SqlClient.SqlCommand)cmd;
            DataTable dt = new DataTable("dataTbl");
            try
            {
                cmd.Connection.Open();
                adapter.FillSchema(dt, SchemaType.Source);
                adapter.Fill(dt);
            }
            finally
            {
                cmd.Connection.Close();
            }
            return dt;
        }

P.S.: I'm not the writer of this code, I just Googled it some time ago.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rami Shareef
Software Developer KATAKIT
Syrian Arab Republic Syrian Arab Republic
I never done anything before

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionpass linq query as an argument? Pin
Member 1083043311-Jun-15 21:20
memberMember 1083043311-Jun-15 21:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161128.1 | Last Updated 5 Apr 2010
Article Copyright 2010 by Rami Shareef
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid