Solved

how to generate datatable from linq query?

Posted on 2011-03-13
3
710 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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 74

Expert Comment

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

Accepted Solution

by:
vivekpv10 earned 500 total points
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

772 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now