C#, LINQ 取得前幾筆資料

在這個範例中,我們使用 LINQ 查詢語法來進行查詢。首先,我們使用 from 子句定義範圍變數 person,然後使用 where 子句過濾符合條件的人,接著使用 orderby 子句按照年齡降序排序,最後使用 select 子句創建一個新的匿名類型,選擇我們感興趣的屬性。最終,我們使用 Take 方法獲取前五個人的結果並將其存儲在 result 變數中,然後通過廻圈列印出來。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class Program {
  6. static void Main() {
  7. List people = new List {
  8. new Person {
  9. Id = 1, Name = "約翰史密斯", Age = 35
  10. }, new Person {
  11. Id = 2, Name = "簡道", Age = 28
  12. }, new Person {
  13. Id = 3, Name = "約翰強生", Age = 42
  14. }, new Person {
  15. Id = 4, Name = "愛麗絲強森", Age = 31
  16. }, new Person {
  17. Id = 5, Name = "鮑勃史密斯", Age = 40
  18. }, new Person {
  19. Id = 6, Name = "傑克強森", Age = 29
  20. },
  21. };
  22. var query = from person in people where person.Age >= 30 && person.Name.StartsWith("約翰") orderby person.Age descending select new {
  23. Id = person.Id, Name = person.Name, Age = person.Age
  24. };
  25. var result = query.Take(5).ToList();
  26. foreach(var person in result) {
  27. Console.WriteLine($"編號:{person.Id},姓名:{person.Name},年齡:{person.Age}");
  28. }
  29. }
  30. }
  31. public class Person {
  32. public int Id {
  33. get;
  34. set;
  35. }
  36. public string Name {
  37. get;
  38. set;
  39. }
  40. public int Age {
  41. get;
  42. set;
  43. }
  44. }

留言

這個網誌中的熱門文章

ORA-12514: TNS: 監聽器目前不知道連線描述區中要求的服務

Oracle 工作排程 DBMS_JOB 筆記

Oracle 例外控制(Exception Control)