在DataTables上使用LINQ进行内部联接

时间:2013-04-27 21:29:15

标签: c# linq inner-join

我有这两个DataTable,customerTableDTcustomerAliasesTableDT。它们都是从这样的数据库中填充的:

customerTableDT = UtilityDataAndFunctions.PerformDBReadTransactionDataTableFormat(String.Format("SELECT * FROM {0}", TableNames.customers));

customerAliasesTableDT = UtilityDataAndFunctions.PerformDBReadTransactionDataTableFormat(String.Format("SELECT * FROM {0}", TableNames.customerAliases));

现在我正在尝试对这两个数据表进行内连接:

var customerNames = from customers in customerTableDT.AsEnumerable()
                    join aliases in customerAliasesTableDT.AsEnumerable on customers.Field<int>("CustomerID") equals aliases.Field<int>("CustomerID")
                    where aliases.Field<string>("Alias").Contains(iString) select customers.Field<string>("Name")

但它给了我这个错误:

The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'.

如果我不得不在SQL中写下我正在尝试做的事情,那很简单:

SELECT * FROM CUSTOMERS C
INNER JOIN CustomerAliases ALIASES ON ALIASES.CustomerID = C.CustomerID
WHERE CA.Alias LIKE %STRING_HERE%

任何帮助?

1 个答案:

答案 0 :(得分:4)

您在AsEnumerable之后错过了括号,因此将其视为方法组,而不是IEnumerable<DataRow>

var customerNames = from customers in customerTableDT.AsEnumerable()
                    join aliases in customerAliasesTableDT.AsEnumerable() on customers.Field<int>("CustomerID") equals aliases.Field<int>("CustomerID")
                    where aliases.Field<string>("Alias").Contains(iString) select customers.Field<string>("Name")