Go Summary of the use of GroupBy Methods in LINQ

Source: Internet
Author: User

Summary of the use of GroupBy Methods in LINQ

Group is often used in SQL, usually to group a field or multiple fields, sum it up, mean value, etc.

The GroupBy method in LINQ also has this capability. Specific implementation look at the code:

Suppose that there is a dataset like the following:

public class Studentscore {public int ID {set; get;}         public string Name {set; get;}         public string Course {set; get;}         public int score {set; get;}     public string Term {set; get;} } list<studentscore> LST = new list<studentscore> () {new Studentscore () {id=1,name= "Zhang San", term= "                 First semester ", course=" Math ", score=80}, New Studentscore () {id=1,name=" Zhang San ", term=" first semester ", course=" Chinese ", score=90}, New Studentscore () {id=1,name= "Zhang San", term= "first semester", course= "中文版", score=70}, New Studentscore ( {id=2,name= "John Doe", term= "first semester", course= "Math", score=60}, New Studentscore () {id=2,name= "John Doe", term= "first semester", Course                 = "Chinese", score=70}, New Studentscore () {id=2,name= "John Doe", term= "first semester", course= "中文版", score=30}, New Studentscore () {id=3,name= "Harry", term= "first semester", course= "Math", score=100}, New Studentscore () {Id=3,name = "Harry", term= "first semester", course= "ChinesE ", score=80}, New Studentscore () {id=3,name=" Harry ", term=" first semester ", course=" 中文版 ", score=80}, NE W Studentscore () {id=4,name= "Zhao Liu", term= "first semester", course= "Math", score=90}, New Studentscore () {id=4,name= "Zhao Liu", Ter m= "First semester", course= "Chinese", score=80}, New Studentscore () {id=4,name= "Zhao Liu", term= "first semester", course= "中文版", score= +}, new Studentscore () {id=1,name= "Zhang San", term= "second semester", course= "Math", score=100}, new STUDENTSC Ore () {id=1,name= "Zhang San", term= "second semester", course= "Chinese", score=80}, New Studentscore () {id=1,name= "Zhang San", term= "second semester"                 , course= "中文版", score=70}, New Studentscore () {id=2,name= "John Doe", term= "second semester", course= "Math", score=90}, New Studentscore () {id=2,name= "John Doe", term= "second semester", course= "Chinese", score=50}, New Studentscore () {id= 2,name= "John Doe", term= "second semester", course= "中文版", score=80}, New Studentscore () {id=3,name= "Harry", term= "second semester", course= "        Math ", score=90},         New Studentscore () {id=3,name= "Harry", term= "second semester", course= "Chinese", score=70}, New Studentscore () {id=3 , name= "Harry", term= "second semester", course= "中文版", score=80}, New Studentscore () {id=4,name= "Zhao Liu", term= "second semester", course= "M                 Ath ", score=70}, New Studentscore () {id=4,name=" Zhao Liu ", term=" second semester ", course=" Chinese ", score=60},  New Studentscore () {id=4,name= "Zhao Liu", term= "second semester", course= "中文版", score=70},};

  

This data set can be imagined as a two-dimensional table in a database.

Example One

Usually we put the grouped data into anonymous objects, because the columns of the grouped data are not necessarily consistent with the original two-dimensional table. Of course, according to the format of the original data is also possible, just select the appropriate type to use.

The first one is simple, just based on the following groupings.

Group, according to the name, statistics sum of the score, the results are placed in the anonymous object. Two ways of writing. The first form of writing Console.WriteLine ("---------The first form of writing"); var studentsumscore_1 = (from L in LST                          group L by l.name into grouped                          grouped. Sum (M = m.score)                          Select new {Name = grouped. Key, Scores = grouped. Sum (M = M.score)}). ToList (); foreach (var l in Studentsumscore_1) {     Console.WriteLine ("{0}: Total score {1}", L.name, L.scores);} The second notation is actually equivalent to the first. The second way of writing Console.WriteLine ("---------The second way of writing"); var studentsumscore_2 = lst. GroupBy (M = m.name)     . Select (k = = new {Name = K.key, Scores = k.sum (L = = l.score)})     . (M = m.scores). ToList (); foreach (var l in studentsumscore_2) {     

Example Two

When the grouped fields are multiple, the fields are usually merged into an anonymous object, and then group by this anonymous object.

Note: After groupby the data into grouped this variable, grouped is actually igrouping<tkey, telement> type, Igrouping<out TKey, out telement> Inherited the Ienumerable<telement>, and one more attribute is the key, which is the original group of keywords, that is, those values are the same field, here is the anonymous object. This key can be obtained in subsequent code to facilitate our programming.

In SQL, multiple fields are separated by commas, and a few more are written directly in LINQ.

Group, according to 2 conditions semester and course, Statistical division evenly, statistical results are placed in anonymous objects. Two ways of writing. Console.WriteLine ("---------The first form of a notation");                        var termavgscore_1 = (from L in LST group L by new {term = l.term, Course = l.course} to grouped Grouped. Average (M = m.score) ascending the grouped. Key.term Descending Select New {term = grouped. Key.term, Course = grouped. Key.course, Scores = grouped. Average (M = M.score)}). ToList (); foreach (var l in Termavgscore_1) {Console.WriteLine ("Semester: {0}, course {1}, evenly divided {2}", L.term, L.course, l.scores);} Console.WriteLine ("---------second notation"); var termavgscore_2 = lst. GroupBy (m = new {term = m.term, Course = M.course}). Select (k = new {term = k.key.term, Course = k.key.course, Scores = k.average (M = M.score)}). (L = l.scores). OrderByDescending (L = l.term);  foreach (var l in termavgscore_2) {Console.WriteLine ("Semester: {0}, course {1}, evenly divided {2}", L.term, L.course, l.scores);}

Example Three

LINQ does not have a having statement in SQL, so a where statement is used to filter the results of a group.

Group, with having query, query evenly >80 student Console.WriteLine ("---------The first form of writing");                   var avgscoregreater80_1 = (from L in LST group L by new {Name = l.name, term = l.term} to grouped where grouped. Average (M = m.score) >=80 the grouped. Average (M = m.score) Descending select new {Name = grouped. Key.name, term = grouped. Key.term, Scores = grouped. Average (M = M.score)}). ToList (); foreach (var l in Avgscoregreater80_1) {Console.WriteLine ("Name: {0}, semester {1}, evenly divided {2}", L.name, L.term, l.scores);} Console.WriteLine ("---------second notation"); This looks more complex, the first groupby, because it is to group more than one field, Www.it165.net therefore constructs an anonymous object, groups the anonymous object, the group gets is actually a ienumberable<igrouping< An anonymous type,studentscore>> such a type. The Where method accepts, and returns the same ienumberable<igrouping< anonymous type,studentscore>> type, where the type of the Where method signature Func delegate is also func< igrouping< anonymous type, studentscore>,bool>, said before, Igrouping<out TKey, out Telement> inherited ienumerable< Telement&gt, so this type can have average,sum and other partiesMethod. var avgscoregreater80_2 = lst. GroupBy (L + = new {Name = l.name, term = l.term}). Where (M = m.average (x = x.score) >= 80). OrderByDescending (L=>l.average (X=>x.score)). Select (L = = new {Name = l.key.name, term = l.key.term, Scores = l.average (M = M.score)}). ToList ();   foreach (var l in Avgscoregreater80_2) {Console.WriteLine ("Name: {0}, semester {1}, evenly divided {2}", L.name, L.term, l.scores);}

Go Summary of the use of GroupBy Methods in LINQ

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.