using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
namespace Csharp
{
class Program
{
class GroupSample1
{
// The element type of the data source.
public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List
Scores;
}
public static List
GetStudents()
{
// Use a collection initializer to create the data source. Note that each element
// in the list contains an inner sequence of scores.
List
students = new List
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List
{97, 72, 81, 60}}, new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List
{75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List
{99, 89, 91, 95}}, new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List
{72, 81, 65, 84}}, new Student {First="Debra", Last="Garcia", ID=115, Scores= new List
{97, 89, 85, 82}} }; return students; } static void Main(string[] args) { var students = GetStudents(); //group by pass or fail var boolQuery = from student in students group student by student.Scores.Average() > 80; foreach (var studentGroup in boolQuery) { Console.WriteLine((studentGroup.Key == true) ? "High Averages" : "Low Averages"); foreach (var student in studentGroup) Console.WriteLine("{0} {1}'s average score is {2}", student.First, student.Last, student.Scores.Average()); } Console.WriteLine("-------------------------------------"); //group by the score rank var groupByScoresQuery = from student in students let avg = (int)student.Scores.Average() group student by (avg == 0 ? 0 : avg / 10) into g orderby g.Key select g; foreach (var studentGroup in groupByScoresQuery) { var avgLowBound = studentGroup.Key * 10; Console.WriteLine("the students' scores between the {0} to {1}", avgLowBound, avgLowBound + 10); foreach (var student in studentGroup) Console.WriteLine("{0} {1}'s average score is {2}", student.First, student.Last, student.Scores.Average()); } } } } }
Group By 的用法
最新推荐文章于 2022-11-09 15:00:16 发布