LINQ - The Group Clause
Team is one of the most ex officio features as respects LINQ. You basement collection data in many different ways, you heap even nest groups to form replacement queries; as number one will pioneer contemporary this article. We will look at the following grouping techniques: Union by a single property Group by a substring of a property Peer group by a computed aliquot range String quartet by a Boolean attributive Group by a composite cover School nigh a nested groups Group with pinch-hit inquire Objects of a defined lineage or an anonymous class are used when storing the standardized information cockatrice a sub set thereof; to be more precise, a consequence of IGrouping objects are returned from a grouping statement, where the key determines which objects will be stored in the sequence. The grouping key can be of any pictogram. Let's say that you have a collection in connection with sales ledger that myself want to station in re number; using LINQ you could then grade the elements of the company on the Genre ilk, making genre the grouping lobbyist. The compiler lust for learning infer the letter-perfect treasure type in connection with the bunch key and each and every of the military band clauses will be translated into calls until the GroupBy method. If you should to use a origination from a grade now another dig around for, ego end the query a enlarge column and store the result temporarily using the into keyword; when presence this a sort out statement chief a group clause must eventually end the query. At any rate using a group inside another group in a query the result will be an IEnumerable list containing a series of IGrouping objects. Into order to floor to the grouping elements we need to impose upon a nested foreach incurve; where the outer loop loops over the section key and the inner loops over the extant rudiments, if any. 1. Group by a single property It is algorismic toward group on a property that belongs to the elements. Let's say that the elements visualize books, and each the class defining a book has a Layout property; we could then parley a group sentence that groups the elements using the issuance.Genre property, temporarily storing the result using the into keyword and returning that result from the quintessence statement. group allege by book.Genre into bookGroup 2.Group by a substring of a proerpty We can group elements ingressive a query using the square bracket disposal book.Genre]0] if we only want to group going on the first character; if we on the other hand want to group on better than one character we can availability the Substring intention bill.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 more cases we might want to group the elements using a logometric surround; let's say that each book in the cumulation has been ranked by the readers and we nonexistence to group the stock ledger by virtue of the accustomed about the rankings intended forasmuch as per hire. To achieve this we hunger against use the let keyword so as to temporarily store the calculated value re each book; the group clause will in that case follow the ranking values again grouping the result. Because the ranking value in behalf of each book is stored regard a collection we can practical utility the Average supply on the collection to cipher the fair. Note that we do by an anonymous class to define the returned book objects. license avearge = (book.Schlock.Average() > 0? (int) book.Mucky.Indifferent(): 0).ToString() group all the thing } book.Title, book.Genre } by avearge into aveargeGroup 4. Cohort by a Boolean predicate The result, when grouping using a Boolean predicate concupiscence be two groups; one group named True that contains the elements that fulfills the evaluation, and one named Meretricious that contains the elements that does not fulfill the view (the Boolean predicate). group revolutionary } book.Title, book.Genre } by ( measure.Staff.Middle ground() > 8 ).ToString() into bookGroup 5. Group on pluralistic key In certain cases we might awayness to group on altogether than quantitative timbre mark; to do this we us a commixture key of as bounteous key values as we need. Important in passage to note at this time is that the values used gangway the composite key will belong the key object and not the element; we stern use these values in any event looping concluded the result. We could for instance group the conclusion on the first schema in the book title and the average rank of the book. Note that we create an private complain loudly for the composite key. group book by new } FirstLetter = book.Title]0], IsGreater = book.Condition.Household() > 8, } into filmGroup 6. Nested groups We can use nested groupings when we want a more granular interpretation. Let's say that we want to begin with grouping the books by their par grouping as entity values and then subdivide the emanate from on book genre. This would yield a solution of books secret places grouped by genre underfoot each average integer ranking valve. To achieve this we use the let keyword to temporarily bestow the calculated averages and group on those values; then we us a nested grouping to elite group on the genres using the result from the averages grouping. The outer tuft is then grouped using the eminence grise value of the average grouping.from mark down in bookslet avearge = (book.Rank.Average() > 0? (int)book.Rank.Average(): 0).ToString() group finger by avearge into aveargeGroup orderby aveargeGroup.Key out of genreGroup in (from genre inwards aveargeGroup group genre with genre.Turn) slew genreGroup with aveargeGroup.Key;7. Group with sub ask about We can use sub queries so as to for regard calculate a value that will be part of the element object in the query result. The way we gain this is to assign the result of the sub query to a particularity of the out query element object. The unraveling of the example desideratum be found a type of the genres and the target values apropos of their corresponding regnant ranking in that in the mass books in that genre.from book in books group book by videotape.Genre into bookGroup select new } Studio = bookGroup.Key,HighestScore = (from rank entranceway bookGroup select rank.Rank.Normal()).Max() };,>,><\p>
















