C# 根据首字母排序单词的雏形示例
2020-11-11 本文已影响0人
Rinaloving
原文档地址:https://www.veryhuo.com/down/html/26615.html
class Program
{
public class Student //声明一个Student类
{
public string First { get; set; } //定义自动属性First表示First Name
public string Last { get; set; } //定义自动属性Last表示Last Name
public int ID { get; set; } //定义自动属性表示学生ID号
}
public static List<Student> GetStudents()
{
// 定义集合GetStudents作为数据源.
List<Student> students = new List<Student>
{
new Student {First="Svetlana", Last="Omelchenko", ID=111},//学生信息
new Student {First="Claire", Last="O'Donnell", ID=112},
new Student {First="Sven", Last="Mortensen", ID=113},
new Student {First="Cesar", Last="Garcia", ID=114}//,
//new Student {First="Debra", Last="Garcia", ID=115}
};
return students;
}
static void Main(string[] args)
{
// 创建LINQ查询数据源 students
List<Student> students = GetStudents();
// 创建LINQ查询
IEnumerable<Student> sortedStudents =
from student in students
orderby student.Last ascending, student.First ascending //先按Lastname排序,再按First排序
select student;
// 执行查询.
Console.WriteLine("排好序的姓和名是:");
foreach (Student student in sortedStudents)
Console.WriteLine(student.Last + " " + student.First);
// 创建分组并排序.
var sortedGroups =
from student in students
orderby student.Last, student.First
group student by student.Last[0] into newGroup//按照Lastname的第一个字母进行分组
orderby newGroup.Key
select newGroup;
// 执行查询.
Console.WriteLine(Environment.NewLine + "分组排序结果是:");
foreach (var studentGroup in sortedGroups)
{
Console.WriteLine("分组的首字母是:"+studentGroup.Key);
foreach (var student in studentGroup)
{
Console.WriteLine(" {0}, {1}", student.Last, student.First);
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
结果:
排好序的姓和名是:
Garcia Cesar
Mortensen Sven
O'Donnell Claire
Omelchenko Svetlana
分组排序结果是:
分组的首字母是:G
Garcia, Cesar
分组的首字母是:M
Mortensen, Sven
分组的首字母是:O
O'Donnell, Claire
Omelchenko, Svetlana