Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8533223
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T09:54:44+00:00 2026-06-11T09:54:44+00:00

i have a linq to dataTable query like this: `var ShowResult = from r

  • 0

i have a linq to dataTable query like this:

`var ShowResult = from r in Result.AsEnumerable()
                             where Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")) > 60
                             orderby Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")) descending 
                             select new
                             {
                                 pascode = r.Field<string>("PAS_CODE"),
                                 melli = r.Field<string>("CODEMELI"),
                                 name = r.Field<string>("NAM"),
                                 family = r.Field<string>("FAMILY"),
                                 bycode = r.Field<string>("BAYGANI"),
                                 jancode = r.Field<string>("CODEJANBAZ"),
                                 darsad = r.Field<int>("DARSAD"),
                                 ostan = r.Field<string>("OSTAN_N"),
                                 vacode = r.Field<string>("VA_CODE"),
                                 moin = r.Field<string>("VA_MOIN"),
                                 onvan = r.Field<string>("TAFZILI"),
                                 aslvam = r.Field<double>("ASLVAM"),
                                 gest = r.Field<double>("GEST"),
                                 //tededGestKol = Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")),
                                 mandeVam = r.Field<double>("MANDE_VAM"),
                                 dPardakht = r.Field<string>("DATE_P")
                             };`<code>

and i added reference System.Data.DataSetExtentions to use CopyToDataTable() method for showing my query result in a dataGrid view but this method didn,t add to my Inellisence,
I also use the MSDN Sample to use this method but this time i got this error :
“Specified Cast is not valid”
Please help me , what can i do to overcom this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T09:54:45+00:00Added an answer on June 11, 2026 at 9:54 am

    CopyToDataTable() only works when your query returns an IEnumerable<‘DataRow>. In your query, you are returning an anonymous type. Anonymous types don’t carry the extension method for CopyToDataTable(). You could just select the entire row like this, assuming Result is a DataTable. Then create your anonymous type.

         public static void Start()
        {
            DataTable Result = new DataTable();
            var ShowResult = from r in Result.AsEnumerable()
                             where Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")) > 60
                             orderby Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")) descending
                             select r;
    
            DataTable newDataTbl = ShowResult.CopyToDataTable();
            var anonType = newDataTbl.AsEnumerable()
                .Select(r => new
                             {
                                 pascode = r.Field<string>("PAS_CODE"),
                                 melli = r.Field<string>("CODEMELI"),
                                 name = r.Field<string>("NAM"),
                                 family = r.Field<string>("FAMILY"),
                                 bycode = r.Field<string>("BAYGANI"),
                                 jancode = r.Field<string>("CODEJANBAZ"),
                                 darsad = r.Field<int>("DARSAD"),
                                 ostan = r.Field<string>("OSTAN_N"),
                                 vacode = r.Field<string>("VA_CODE"),
                                 moin = r.Field<string>("VA_MOIN"),
                                 onvan = r.Field<string>("TAFZILI"),
                                 aslvam = r.Field<double>("ASLVAM"),
                                 gest = r.Field<double>("GEST"),
                                 //tededGestKol = Convert.ToInt32(r.Field<double>("ASLVAM") / r.Field<double>("GEST")),
                                 mandeVam = r.Field<double>("MANDE_VAM"),
                                 dPardakht = r.Field<string>("DATE_P")
                             }
                       );
        }
    

    In lieu of the former method, you could use the following extension methods to create a Datatable from a List<‘T>.

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Data;
            using System.ComponentModel;
            using System.Reflection;
    
            namespace Common
            {
                public static class DataTableExtensions
                {
                    public static DataTable ConvertToDataTable<T>(this IList<T> data)
                    {
                        PropertyDescriptorCollection properties =
                            TypeDescriptor.GetProperties(typeof(T));
                        DataTable table = new DataTable();
                        foreach (PropertyDescriptor prop in properties)
                            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                        foreach (T item in data)
                        {
                            DataRow row = table.NewRow();
                            foreach (PropertyDescriptor prop in properties)
                                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                            table.Rows.Add(row);
                        }
                        table.AcceptChanges();
                        return table;
                    }
    
                    public static DataRow ConvertToDataRow<T>(this T item, DataTable table)
                    {
                        PropertyDescriptorCollection properties =
                            TypeDescriptor.GetProperties(typeof(T));
                        DataRow row = table.NewRow();
                        foreach (PropertyDescriptor prop in properties)
                            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                        return row;
                    }
    
                    public static T ConvertToEntity<T>(this DataRow tableRow) where T : new()
                    {
                        // Create a new type of the entity I want
                        Type t = typeof(T);
                        T returnObject = new T();
    
                        foreach (DataColumn col in tableRow.Table.Columns)
                        {
                            string colName = col.ColumnName;
    
                            // Look for the object's property with the columns name, ignore case
                            PropertyInfo pInfo = t.GetProperty(colName.ToLower(),
                                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    
                            // did we find the property ?
                            if (pInfo != null)
                            {
                                object val = tableRow[colName];
    
                                // is this a Nullable<> type
                                bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
                                if (IsNullable)
                                {
                                    if (val is System.DBNull)
                                    {
                                        val = null;
                                    }
                                    else
                                    {
                                        // Convert the db type into the T we have in our Nullable<T> type
                                        val = Convert.ChangeType(val, Nullable.GetUnderlyingType(pInfo.PropertyType));
                                    }
                                }
                                else
                                {
                                    // Convert the db type into the type of the property in our entity
                                    SetDefaultValue(ref val, pInfo.PropertyType);
                                    if (pInfo.PropertyType.IsEnum && !pInfo.PropertyType.IsGenericType)
                                    {
                                        val = Enum.ToObject(pInfo.PropertyType, val);
                                    }
                                    else
                                        val = Convert.ChangeType(val, pInfo.PropertyType);
                                }
                                // Set the value of the property with the value from the db
                                if (pInfo.CanWrite)
                                    pInfo.SetValue(returnObject, val, null);
                            }
                        }
    
                        // return the entity object with values
                        return returnObject;
                    }
    
                    private static void SetDefaultValue(ref object val, Type propertyType)
                    {
                        if (val is DBNull)
                        {
                            val = GetDefault(propertyType);
                        }
                    }
    
                    public static object GetDefault(Type type)
                    {
                        if (type.IsValueType)
                        {
                            return Activator.CreateInstance(type);
                        }
                        return null;
                    }
    
                    public static List<T> ConvertToList<T>(this DataTable table) where T : new()
                    {
                        Type t = typeof(T);
    
                        // Create a list of the entities we want to return
                        List<T> returnObject = new List<T>();
    
                        // Iterate through the DataTable's rows
                        foreach (DataRow dr in table.Rows)
                        {
                            // Convert each row into an entity object and add to the list
                            T newRow = dr.ConvertToEntity<T>();
                            returnObject.Add(newRow);
                        }
    
                        // Return the finished list
                        return returnObject;
                    }
                }
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Linq query that looks something like this: var myPosse = from
I have a LINQ query to a DataTable : var list = from row
I have some LINQ code that generates a list of strings, like this: var
how to extract DataTable or DataSet from Linq Query or List. e.g I have
I have a table, generated from a LINQ query on a datatable, which has
Q: I have a DataTable result from the following query: SELECT UNIQUE a.crsnum_e ,
I have a linq to entities query (EF 4.3) var query = from item
I have linq request. I need get item.Title in select. how do this? var
I have a LINQ to Entity query that is running really slow. This query
I have this linq query that works well (although it may be written better,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.