Join Operator


In an object oriented program, objects that are related to each other will typically be linked up with object references which are easy to navigate. The same usually does not hold true for external information sources, where data entries often have no option but to “point” to each other symbolically, with IDs or other data that can uniquely identify the entity pointed to. The concept of joins refers to the operation of bringing the elements of a sequence together with the elements they “match up with” from another sequence.









string[] names = { "Burke", "Connor", "Frank", "Everett",

                   "Albert", "George", "Harris", "David" };


var query = names.Join(people, n => n, p => p.Name, (n,p) => p);



This is a bit of a mouthful, but see how the pieces fit together:

The Join method is called on the “outer” data source, names. The first argument is the “inner” data source, people. The second and third arguments are lambda expressions to extract keys from the elements of the outer and inner sources, respectively. These keys are what the Join method uses to match up the elements. Here we want the names themselves to match the Name property of the people. The final lambda expression is then responsible for producing the elements of the resulting sequence: It is called with each pair of matching elements n and p, and is used to shape the result. In this case we choose to discard the n and return the p. The end result is the list of Person elements of people whose Name is in the list of names.

A more powerful cousin of Join is the GroupJoin operator. GroupJoin differs from Join in the way the result shaping lambda expression is used: Instead of being invoked with each individual pair of outer and inner elements, it will be called only once for each outer element, with a sequence of all of the inner elements that match that outer element. To make that concrete:









string[] names = { "Burke", "Connor", "Frank", "Everett",

                   "Albert", "George", "Harris", "David" };


var query = names.GroupJoin(people, n => n, p => p.Name,                  

           (n, matching) =>

                      new { Name = n, Count = matching.Count() }

);



 


This call produces a sequence of the names you started out with paired with the number of people who have that name. Thus, the GroupJoin operator allows you to base your results on the whole “set of matches” for an outer element.

                    

Aspnet Related Tutorials

...more

New Aspnet Resources

...more

Copyright © 2012 VisualBuilder. All rights reserved