Skip to main content
 首页 » 编程设计

c#之在数据表上使用 LINQ 进行内部联接

2024年02月13日9zhwl

我有这 2 个数据表,customerTableDT 和 customerAliasesTableDT。它们都是从这样的数据库中填充的:

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% 

有什么帮助吗?

请您参考如下方法:

您在 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")