David Rasuli
David Rasuli

Reputation: 832

Fill DataTable with values from a Linq Query

I have a linq Query which works well.

var data = from c in context.C
                   where c.ID == 1
                   select new
                   {
                       cc = c.CC,
                       oc= c.OC,
                       ec = c.EC
                   };

I wish to load the information from this query to my datatable.

If there is an option of doing it without extending any method I'd be very happy to hear them but any help would be appreciated.

Regards, David

Upvotes: 0

Views: 3054

Answers (2)

David Rasuli
David Rasuli

Reputation: 832

OK I believe I found it:

var data = from c in context.C
               where c.ID == 1
               select new
               {
                   cc = c.CC,
                   oc= c.OC,
                   ec = c.EC
               };

adding an extension method:

use System.Reflection;
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
    {
        DataTable dtReturn = new DataTable();

        // column names 
        PropertyInfo[] oProps = null;

        if (varlist == null) return dtReturn;

        foreach (T rec in varlist)
        {


            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;
    }

Now to use it :

DataTable dt = LINQToDataTable(data);

Upvotes: 0

raveturned
raveturned

Reputation: 2677

From .Net 3.5 onwards, the CopyToDataTable method is probably what you're after.

Upvotes: 3

Related Questions