Solved

how to generate datatable from linq query?

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

763 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