Solved

how to generate datatable from linq query?

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

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…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

710 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