누군가 LINQ/람다 식을 사용하여 왼쪽 조인 작업을 수행하는 방법을 보여줄 수 있습니까?LINQ를 사용하여 왼쪽으로 조인
8
A
답변
6
MSDN의 LINQ to SQL samples page에는이를 수행하는 방법의 예가 나와 있습니다. 코드는 LINQ to Objects와 거의 동일해야합니다.
여기서 키는 DefaultIfEmpty
입니다.
Dim q = From e In db.Employees _
Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
From o In ords.DefaultIfEmpty _
Select New With {e.FirstName, e.LastName, .Order = o}
C#으로 변환하는 데 도움이 필요하면 질문하십시오.
4
여기에 LINQ에 example of a left join이 있습니다.
예를 들어
0
:이 지정된 사용자 (iduser 키)과 일치하지 않는 경우
IQueryable<aspnet_UsersInRole> q = db.aspnet_Roles
.Select(p => p.aspnet_UsersInRoles
.SingleOrDefault(x => x.UserId == iduser));
가 null로, 당신에게
0
방법 I를 asp.net 회원의 역할 목록을 줄 것이다 내가 좋아하는 것으로는 과 InnerCollection.DefaultIfEmpty()
을 결합하는 것이 좋습니다. "C# Statements"모드를 사용하여 LINQPad에서 다음을 실행할 수 있습니다. 이 실험을하는 동안
var teams = new[]
{
new { Id = 1, Name = "Tigers" },
new { Id = 2, Name = "Sharks" },
new { Id = 3, Name = "Rangers" },
};
var players = new[]
{
new { Name = "Abe", TeamId = 2},
new { Name = "Beth", TeamId = 4},
new { Name = "Chaz", TeamId = 1},
new { Name = "Dee", TeamId = 2},
};
// SelectMany generally aggregates a collection based upon a selector: from the outer item to
// a collection of the inner item. Adding .DefaultIfEmpty ensures that every outer item
// will map to something, even null. This circumstance makes the query a left outer join.
// Here we use a form of SelectMany with a second selector parameter that performs an
// an additional transformation from the (outer,inner) pair to an arbitrary value (an
// an anonymous type in this case.)
var teamAndPlayer = teams.SelectMany(
team =>
players
.Where(player => player.TeamId == team.Id)
.DefaultIfEmpty(),
(team, player) => new
{
Team = team.Name,
Player = player != null ? player.Name : null
});
teamAndPlayer.Dump();
// teamAndPlayer is:
// {
// {"Tigers", "Chaz"},
// {"Sharks", "Abe"},
// {"Sharks", "Dee"},
// {"Rangers", null}
// }
, 나는 가끔 당신이 익명 형식의 인스턴스에
player
의 널 (null) 검사를 생략 할 수 있음을 발견했다. 나는 이것이 데이터베이스에서 LINQ-to-SQL을 사용하는 경우라고 생각한다. (이 배열 대신 LINQ-to-objects 또는 something으로 생각한다.) null check의 누락이 LINQ에서 작동한다고 생각한다. -to-SQL은 쿼리가 SQL
LEFT OUTER JOIN
으로 변환되므로 바깥 쪽 항목과 null을 결합하는 것으로 바로 넘어갑니다. 익명 객체의 속성 값은 nullable이어야하므로,
int
을 안전하게 포함하려면 다음과 같이 입력해야합니다.
new { TeamId = (int?)player.TeamId }
0
잘 알려진 왼쪽 조인을 재현하려고합니다. 여기서 b 키 null이며, 내가 가진 결과 (가입 그냥 왼쪽을 만들기 위해 수정할 수 있습니다 약간의 상상력과 함께)이 확장 방법입니다!
public static class extends
{
public static IEnumerable<T> LefJoinBNull<T, TKey>(this IEnumerable<T> source, IEnumerable<T> Target, Func<T, TKey> key)
{
if (source == null)
throw new ArgumentException("source is null");
return from s in source
join j in Target on key.Invoke(s) equals key.Invoke(j) into gg
from i in gg.DefaultIfEmpty()
where i == null
select s;
}
}
을 모든 LINQ 람다 익스프레스를 타고 – mquander
하하 그래도,보고보다는이. 게시물 downvotes에 의해 망치질, 나는 그것이 올바른 것으로 보이기 때문에, 나는 괜찮은 영어로 질문을 다시 작성 줄 알았는데. – Noldorin
@mquander : :: 원본을 읽어보십시오 질문의 : : : 그리고 당신의 의견은 웃음을 가져 왔습니다. – Brian