Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Skip() trong C# LINQ

Skip() bỏ qua N phần tử đầu tiên của chuỗi, trả về các phần tử còn lại. Thường dùng cho phân trang (pagination) hoặc loại bỏ header.

Ví dụ minh họa

Mảng điểm:

int[] marks = { 80, 55, 79, 99 };

Sắp xếp giảm dần, bỏ qua 2 phần tử đầu:

IEnumerable<int> selMarks = marks.AsQueryable()
    .OrderByDescending(s => s)
    .Skip(2);

Mã nguồn hoàn chỉnh

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

public class Demo
{
    public static void Main()
    {
        int[] marks = { 80, 55, 79, 99 };
        IEnumerable<int> selMarks = marks.AsQueryable()
            .OrderByDescending(s => s)
            .Skip(2);

        Console.WriteLine("Đã bỏ qua 2 học sinh đầu...");
        foreach (int res in selMarks)
            Console.WriteLine(res);
    }
}

Kết quả dự kiến

79
55

Lưu ý: Code gốc có lỗi typo console.WriteLine (thiếu chữ C in hoa). Đã sửa trong ví dụ trên.