Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

how to generate datatable from linq query?

Posted on 2011-03-13
3
Medium Priority
?
721 Views
Last Modified: 2013-12-17
hi,

I am trying to select data from datatable using linq, now the problem I want to put selected data in datatable schema, I found a ready class to create datatable from implemented IEnumerable returned query, but that generate errors, so how can I create datatable from that query?

here is my try:

 
private DataTable GetInvoicesForCustomer(string id)
        {
            var invoices = (from invoice in dtCustomersInvoices.AsEnumerable()
                            where invoice.Field<int>("id").ToString() == id
                            select invoice);
            if (invoices == null) return null;
            DataTable dt = invoices.CreateDataTable("SelectedInvoicesTable");
            return null;
        }

Open in new window


 
public static class HelperUtils
    {
        // From the Book Programming Microsoft Linq in Microsoft .Net Framework 4
        // By Paolo Pialorsi and Marco Russo
        public static DataTable CreateDataTable<T>(this IEnumerable<T> query, string tableName)
        {
            DataTable table = new DataTable(tableName);
            var fields = typeof(T).GetProperties();

            // Create Columns
            foreach (var field in fields)
            {
                DataColumn column = new DataColumn(field.Name);

                //column.AllowDBNull = (typeof(T).IsSubclassOf(typeof(ValueType))) 
                //    ? IsNullableType(typeof(T)) 
                //    : true;

                // This line modified from original the original line is above
                column.AllowDBNull = (typeof(T).IsSubclassOf(typeof(ValueType)))
                    ? (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))
                    : true;
                table.Columns.Add(column);
            }

            // Copy rows
            foreach (var row in query)
            {
                object[] values = new object[fields.Length];
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = fields[i].GetValue(row, null);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }

Open in new window



any help please?
0
Comment
Question by:njgroup
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35121757
Would this be simpler?
private DataTable GetInvoicesForCustomer(string id)
{
    DataTable invoices = (from invoice in dtCustomersInvoices.AsEnumerable()
                          where invoice.Field<int>("id").ToString() == id
                          select invoice).AsDataview().Table;
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35121759
That should be "AsDataView()", with a capital "V".
0
 
LVL 5

Accepted Solution

by:
vivekpv10 earned 2000 total points
ID: 35127260
for converting linq result into a datatable,use this function..
eg.
var drevlinq = from drelinq_obj in context.drev where userid == drelinq_obj.user_master.user_id select new { drelinq_obj.dreid };
 DataTable devtab = LINQToDataTable(drevlinq);
Public DataTable LINQToDataTable<T>(System.Collections.Generic.IEnumerable<T> varlist)
    {
        DataTable dtReturn = new DataTable();

        // column names 
        PropertyInfo[] oProps = null;

        if (varlist == null) return dtReturn;
    

        foreach (T rec in varlist)
        {
            // Use reflection to get property names, to create table, Only first time, others 
            //   will follow 
            if (oProps == null)
            {
                oProps = ((Type)rec.GetType()).GetProperties();
                foreach (PropertyInfo pi in oProps)
                {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                    == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }

                    dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                }
            }

            DataRow dr = dtReturn.NewRow();

            foreach (PropertyInfo pi in oProps)
            {
                dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                (rec, null);
            }

            dtReturn.Rows.Add(dr);
        }
        return dtReturn;
    }

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question