C#, LINQ 取得前幾筆資料
在這個範例中,我們使用 LINQ 查詢語法來進行查詢。首先,我們使用 from 子句定義範圍變數 person,然後使用 where 子句過濾符合條件的人,接著使用 orderby 子句按照年齡降序排序,最後使用 select 子句創建一個新的匿名類型,選擇我們感興趣的屬性。最終,我們使用 Take 方法獲取前五個人的結果並將其存儲在 result 變數中,然後通過廻圈列印出來。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Program {
- static void Main() {
- List people = new List {
- new Person {
- Id = 1, Name = "約翰史密斯", Age = 35
- }, new Person {
- Id = 2, Name = "簡道", Age = 28
- }, new Person {
- Id = 3, Name = "約翰強生", Age = 42
- }, new Person {
- Id = 4, Name = "愛麗絲強森", Age = 31
- }, new Person {
- Id = 5, Name = "鮑勃史密斯", Age = 40
- }, new Person {
- Id = 6, Name = "傑克強森", Age = 29
- },
- };
- var query = from person in people where person.Age >= 30 && person.Name.StartsWith("約翰") orderby person.Age descending select new {
- Id = person.Id, Name = person.Name, Age = person.Age
- };
- var result = query.Take(5).ToList();
- foreach(var person in result) {
- Console.WriteLine($"編號:{person.Id},姓名:{person.Name},年齡:{person.Age}");
- }
- }
- }
- public class Person {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public int Age {
- get;
- set;
- }
- }
留言
張貼留言