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

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

Select() chiếu (project) mỗi phần tử của chuỗi thành dạng mới. Hỗ trợ lambda với index để truy cập vị trí phần tử.

Ví dụ minh họa

Mảng văn phòng phẩm:

string[] stationery = { "diary", "board", "pencil", "whiteboard" };

Lấy substring từ đầu đến vị trí index+3:

var res = stationery.AsQueryable()
    .Select((item, index) => new { result = item.Substring(0, index + 4) });

Mã nguồn hoàn chỉnh

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

public class Demo
{
    public static void Main()
    {
        string[] stationery = { "diary", "board", "pencil", "whiteboard" };
        var res = stationery.AsQueryable()
            .Select((item, index) => new { result = item.Substring(0, index + 4) });

        foreach (var str in res)
            Console.WriteLine("{0}", str);
    }
}

Kết quả đầu ra

{ result = diar }
{ result = board }
{ result = pencil }
{ result = whitebo }

Lưu ý: index bắt đầu từ 0. Cần đảm bảo item.Length > index + 4 để tránh ngoại lệ.