加入LINQ查询语法:从右侧向左侧

时间:2019-04-18 09:17:14

标签: c# linq join linq-to-entities linq-query-syntax

我有一个需要联接两个表的场景:

A

|---------------------|------------------|
|          ID         |        Name      |
|---------------------|------------------|
|          1          |        John      |
|---------------------|------------------|
|          2          |        Matt      |
|---------------------|------------------|
|          3          |        Emma      |
|---------------------|------------------|

B

|---------------------|------------------|
|          ID         |        Text      |
|---------------------|------------------|
|          1          |  blah blah John  |
|---------------------|------------------|
|          2          | this is some data|
|---------------------|------------------|
|          3          | My name is Jeff  |
|---------------------|------------------|

我需要使用LINQ的查询语法来连接这两个表。

左表必须是表A。

尽管我需要根据“文本”列是否包含表A中“名称”列中的文本进行加入。

代码应如下所示:

var result = from ta in A
             join tb in B on tb.Text.Contains(ta.Name)

我似乎无法在联接的左侧使用tb

我只能使用ta

tb在联接的右侧。

有什么办法可以切换它,以便可以在左侧使用tb

1 个答案:

答案 0 :(得分:3)

LINQ中的联接只能与相等匹配一起使用。但是您可以结合使用SelectManyWhere的方法。它将本质上按条件进行联接。

在查询语法中,它是这样的:

from ta in A
from tb in B
where tb.Text.Contains(ta.Name)
// the rest of your query

另请参阅Perform custom join operations

相关问题