Solved

how to generate datatable from linq query?

Posted on 2011-03-13
3
712 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
  • 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 500 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

770 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