Linq group

时间:2023-03-08 16:55:06

using System;
using System.Collections.Generic;
using System.Linq;

public class MyClass
{
public static void RunSnippet()
{
var students = new[]
{
new {LName = "Jones",FName = "Mary",Age = 19,Major = "History"},
new {LName = "Smith",FName = "Bob",Age = 20,Major = "CompSci"},
new {LName = "Fleming",FName = "Carol",Age = 21,Major = "History"},
};
var query = from student in students
group student by student.Major;
foreach (var s in query)
{
Console.WriteLine("{0}",s.Key);
foreach( var t in s)
Console.WriteLine(" {0} {1}",t.LName,t.FName);
}
}

#region Helper methods

public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}

private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}

private static void RL()
{
Console.ReadLine();
}

private static void Break()
{
System.Diagnostics.Debugger.Break();
}

#endregion
}