Linq outer join

I am new to Linq for an object and ask a question about the from clause when used in two contexts:

1) to perform cross-connect, such as the request below

  var q1 = from person in people from job in jobs select new {person, job} 

2) to perform an external connection

  var q2 = from person in people join pet in pets on person equals pet.Owner into gj from subpet in gj select new { OwnerName = person.FirstName, PetName = subpet.Name }; 

Does the second sentence cross-join or is it contextually evaluated? because q1 will produce people.Count * jobss.Count element but q2 will produce only people.Count

+4
source share
3 answers

According to MS documentation, to make the second request a left outer join, you must use the DefaultIfEmpty method, as shown here . The from clause always evaluates the same thing: it returns every element in the sequence, whether it will be either a predefined source or a context variable.

EDIT: I will try to explain from the very beginning. First you join (team up to be specific) people and pets. Then you select from the resulting collection (actually a set of characters) for the new anonymous object, getting the name of the person (from the gj set element) and the name of the sub-floor (for each of the pets in the gj set element). I think the second one does not execute crossjoin, because it selects from gj, and each person is already part of the set gj element. If you call the gj.DefaultIfEmpty () method in the second of the sentence, then a person without pets will be added to the result set (with an empty basket of pets inside the gj set element). You can read the following articles to better understand this:

+3
source

join usually used to correlate elements of two sequences based on a matching key, so it is usually an inner join, but it depends on what you define as a match, for example, the following will cross-join:

 List<int> A = new List<int> { 1, 2, 3, 4, 5 }; List<int> B = new List<int> { 1, 2, 3, 4, 5 }; var c = (from a in A join b in B on 1 equals 1 select new { a, b }).ToList(); 
0
source

From is evaluated based on context. If this is not the case, you will not be able to use context variables such as gj . But if you do not use this context, as in the first request, it behaves in the same way as a cross-connection.

You say that the second query gives you an unexpected number of elements. Maybe you should not focus on this, but on what elements you get and how it differs from what you expect.

0
source

Source: https://habr.com/ru/post/1394722/