Linq left outer join

依然范特西╮ 提交于 2019-12-19 10:28:07

问题


I ultimately what I needed is generic function which would take two datatable and and 2 tablekeys and return Joined datatable. So here is my first step to solve it.

How Can I write Linq example of following T-SQL example in VB?

SELECT * FROM
Table1
LEFT OUTER JOIN
Table2
ON Table1.key = Table2.key

回答1:


It would be something like this:

Dim JoinedResult = From t1 In Table1 
    Group Join t2 In Table2 
       On t1.key Equals t2.key 
       Into RightTableResults = Group 
    From t2 In RightTableResults.DefaultIfEmpty 
    Select t1.Prop1, 
       t2.Prop2        

I'm not a VB guy (anymore), but I think this would work.




回答2:


You can simply use the existing Join method

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
    this IEnumerable<TOuter> outer,
    IEnumerable<TInner> inner,
    Func<TOuter, TKey> outerKeySelector,
    Func<TInner, TKey> innerKeySelector,
    Func<TOuter, TInner, TResult> resultSelector
)

eg:

table1.Join(table2, t1 => t1.Key, t2 => t2.Key, (t1, t2) => new { Table1 = t1, Table2 = t2 });

can find more overloads and examples http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx

Pardon me for c# examples



来源:https://stackoverflow.com/questions/5740700/linq-left-outer-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!