简体   繁体   中英

LINQ - Convert LINQ select to DataTable

I have a class that does some validation on the data. I want to reuse that class from a different place. I cant change that class. It goes something like:

public static List<string> Validate(DataTable CurrentMasterTable, Dictionary<string, string[]> LocalMasterRuleSet)
    {...}

In its own it works just fine.

Issue is in the following. From another place in the project, to use that class, I must send it DataTable object, so it can do its magic.

How can I use LINQ, make selection on the table and send it as DataTable? I have this code to begin with:

  var listOfSinglePropertyNames = (from x in dbContext.tbl_mytable.AsEnumerable()                                             select x);

        IEnumerable<tbl_mytable> query = listOfSinglePropertyNames;

How do I convert the query to DataTable object? Reading other posts, I have seen I should use CopyToDataTable();

But I am not having any success.

Using LINQ to datatable. Adapt this code for your needings:

 // Query the SalesOrderHeader table for orders placed 
// after August 8, 2001.
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM