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

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

SelectMany() làm phẳng (flatten) các chuỗi lồng nhau thành một chuỗi đơn. Thường dùng để: biến mảng chuỗi thành mảng ký tự, flatten list of lists.

Ví dụ minh họa

Mảng chuỗi:

string[] str = { "Mobile", "Laptop", "Tablet" };

Chuyển thành mảng ký tự đơn:

var res = str.SelectMany(item => item.ToCharArray());

Mã nguồn hoàn chỉnh

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

public class Demo
{
    public static void Main()
    {
        string[] str = { "Mobile", "Laptop", "Tablet" };
        var res = str.SelectMany(item => item.ToCharArray());

        Console.WriteLine("Chuỗi chuyển thành mảng ký tự: ");
        foreach (char letter in res)
            Console.Write(letter);
    }
}

Kết quả đầu ra

Chuỗi chuyển thành mảng ký tự:
MobileLaptopTablet

Ứng dụng khác: orders.SelectMany(o => o.Items) - lấy tất cả items từ tất cả orders.