简体   繁体   中英

How to run Linq on DataTable with SQL like 'IN' and return DataTable C#?

I'm trying to extract specific error lines from a DataTable:

In SQL this is my idea:

SELECT 
*
FROM [Main].[tableData] AS [D] 
WHERE [D].[Row Number] IN (
-- List<int> errorLineNumbers Here
)

Here is my C#:

DataTable mainDataTable = GetData();

List<int> errorLineNumbers errorLineNumbers = GerErrorLineNumbers(mainDataTable);

// This Crashes
DataTable errorDataTable = (from main in mainDataTable.AsEnumerable()
                            where main.Field<int>("Row Number").Equals(errorLineNumbers)
                            select main).CopyToDataTable<DataRow>();

This is the Exception: InvalidCastException

Specified cast is not valid.

I don't have a lot of experience with this. Any help would be appreciated.

In the where clause, you are trying to equal an int (the field value) to a List<int> object - naturally a cast will be attempted an then fail. Instead, try the following:

DataTable errorDataTable = (from main in mainDataTable.AsEnumerable()
                            where errorLineNumbers.Contains(main.Field<int>("Row Number"))
                            select main).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