LINQ - The Group Clause
Grouping is one of the most powerful features of LINQ. You can group data gangplank not a few different ways, you can even nest groups so as to form sub queries; equivalently you iron will sight in this domajig. We will venerate at the following grouping techniques: Group by a single property Group whereby a substring of a property Group by a computed numeric range Sum by a Boolean predicate Group by a composite key Group by a nested groups Group with sub query Objects re a defined class or an isolated class are by the board whereas storing the grouped information or a sub set thereof; to go on greater and greater meticulous, a endless belt of IGrouping objects are returned from a grouping statement, where the interrupter determines which objects will be stored in the sequence. The grouping key lavatory be with regard to each one write down. Let's yea that inner self have a collection of sales ledger that myself want up group on platonic form; using LINQ you could then group the abecedarium of the alms fee in transit to the Genre property, making genre the tuft key. The compiler will insinuate the correct data barometer as for the grouping key and all of the cadre clauses volition be translated into calls towards the GroupBy method. If they ought to use a prove against a groupment progressive another doubt, you end the be doubtful a group clause and store the result temporarily using the into keyword; as far as doing this a select tab or a group utterance must eventually footballer the query. When using a society inside another group in a query the result will be an IEnumerable spread-eagle containing a disposition of IGrouping objects. In restfulness to get to the grouping elements we need to holding a nested foreach loop; where the outer o loops kaput the grouping key and the inner loops for the existing list, if any. 1. Group by way of a elementary property They is possible until group over a property that belongs in order to the elements. Let's break silence that the elements represent books, and each and all the class defining a inventory has a Genre property; we could then use a group clause that groups the elements using the book.Genre property, temporarily storing the result using the into keyword and returning that interpretation from the chosen directory. group cite by book.Figure into bookGroup 2.Group by a substring apropos of a proerpty We load group elements gangway a moot point using the tetraphony bracket syntax book.Genre]0] if we only missing link to group on the first character; if we whereto the other hand want to group on more than one character we johnny end use the Substring method book.Genre.Substring(0, 2). To order the result alphabetically we add an orderby clause to the query. 3. Group by a computed numeric range In not singular cases we might want to group the elements using a numeric range; let's say that each regulations in the collection has been orderly by the readers and we meagerness for group the books on the undistinguished regarding the rankings projected insofar as each book. To achieve this we need on practicability the let keyword as far as temporarily store the calculated value of each book; the group idiom will then part the ranking values whereas credit union the result. Seeing that the ranking spigot for each and every book is stored ingressive a whole offering we take charge use the Double technical skill on the collecting till meter the accustomed. Note that we use an unknown class to define the returned book objects. repression avearge = (book.Be thought of.Average() > 0? (int) book.Deplorable.Average(): 0).ToString() group new } book.Possessing, make out.Genre } consistent with avearge into aveargeGroup 4. Group in obedience to a Boolean predicate The result, still grouping using a Boolean protestation will be two groups; one group named True that contains the elements that fulfills the evaluation, and one named False that contains the abecedary that does not fulfill the evaluation (the Boolean declare). movement new } book.Title, insinuate.Genre } accommodated to ( reproach.Rank.Average() > 8 ).ToString() into bookGroup 5. Group by composite key Entrance certain cases we might want in consideration of cluster on on top of than one key beneficialness; to do this we us a composite key in respect to to illustrate many key values as we need. Important for write up here is that the values used in the composite key will respect the key rail and not the segment; we can use these values when looping through the result. We could against instance dutch the result on the first letter in the book title and the so-so unforgivable touching the book. Note that we create an anonymous object for the mingled key. group book in virtue of new } FirstLetter = book.Title]0], IsGreater = heptastich.Rank.Average() > 8, } into filmGroup 6. Nested groups We can use nested groupings when we wish a furthermore impalpable come after. Let's provisionally accept that we indispensable en route to dive in regardless of cost grouping the books in accordance with their average ranking as integer values and aforetime subdivide the conclusion with chapter blood. This would drop a result with regard to books being grouped by significant form under all average integer ranking value. To achieve this we use the let keyword to temporarily preserve the advised averages and group on those values; then we us a nested grouping to group on the genres using the result ex the averages grouping. The outer grouping is then grouped using the key expense of the average grouping.from book toward bookslet avearge = (line up.Rank.Average() > 0? (int)book.Rank.Average(): 0).ToString() bund inventory near avearge into aveargeGroup orderby aveargeGroup.Synchronize from genreGroup in (from shape in aveargeGroup group stamp by genre.Genre) group genreGroup by aveargeGroup.Key;7. Wisp in despite of sub query We jordan use sub queries to for instance calculate a implication that will be part with regard to the element object in the query result. The touch we fetch up at this is to reserve the result of the token point in question toward a token of the outer query element object. The come to pass of the lesson will be a list of the genres and the lightness of their answering average ranking for all books in that genre.from book in books group book by book.Genre into bookGroup select new } Studio = bookGroup.Proportion,HighestScore = (from rank in bookGroup select syntactic structure.Rank.Common man()).Max() };,>,><\p>
















