哈哈 先獻上之前寫的
然後我覺得很需要這個應用程式 來練習
https://www.linqpad.net/
不像VS一樣很笨重
有些版本不用安裝可以帶著走,想在哪寫就在哪寫
可以不用建立專案甚至不用寫Class,只要寫你想要測試的程式碼即可(Expression、Statement)
還可以把程式碼片段(snippet)存起來當作範例使用~
之前沒介紹到LINQ的Lambda查詢法
所以來補充一下
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
List<Student> students = new List<Student>
{
new Student { StudentID = 1, FirstName = "John", LastName = "Doe", Age = 20 },
new Student { StudentID = 2, FirstName = "Alice", LastName = "Smith", Age = 22 },
new Student { StudentID = 3, FirstName = "Bob", LastName = "Johnson", Age = 21 },
new Student { StudentID = 4, FirstName = "Eve", LastName = "Davis", Age = 23 },
};
// 1. 查詢所有學生
var allStudents = from student in students select student;
// 2. 過濾學生,只選擇年齡大於21的學生
var adultStudents = from student in students where student.Age > 21 select student;
// 3. 按姓氏升序排序學生
var sortedStudents = from student in students orderby student.LastName ascending select student;
還要寫一堆英文是不是超眼花
後專案中團隊有用到這寫法 我覺得必學一下的Lambda運算子就是 =>
圖例:
範例:
使用 Lambda 表達式進行查詢
// 1. 查詢所有學生
var allStudents = students;
// 2. 過濾學生,只選擇年齡大於21的學生
var adultStudents = students.Where(student => student.Age > 21);
// 3. 按姓氏升序排序學生
var sortedStudents = students.OrderBy(student => student.LastName);
Lambda 表達式提供了一種緊湊的語法來定義查詢條件和數據,讓你的code更加簡潔和實用喔~!
參考來源:
LINQPad: 每個.NET工程師都要有的一隻箭