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

Cách flatten list dùng LINQ C#

Flatten list nghĩa là chuyển đổi List<List<T>> thành List<T>. Ví dụ, xét List<List<int>> cần chuyển thành List<int>.

SelectMany trong LINQ dùng để project mỗi element của sequence thành IEnumerable<T> và sau đó flatten các resulting sequences thành một sequence. Nghĩa là SelectMany operator kết hợp records từ sequence của results và convert thành một result.

Dùng SelectMany

Ví dụ

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

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            List<List<int>> listOfNumLists = new List<List<int>> { 
                new List<int> { 1, 2 }, 
                new List<int> { 3, 4 } 
            }; 
            
            var numList = listOfNumLists.SelectMany(i => i); 
            
            Console.WriteLine("Numbers in the list:"); 
            foreach (var num in numList) { 
                Console.WriteLine(num); 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Output

Numbers in the list: 1 2 3 4

Dùng Query Syntax

Ví dụ

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

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            List<List<int>> listOfNumLists = new List<List<int>> { 
                new List<int> { 1, 2 }, 
                new List<int> { 3, 4 } 
            }; 
            
            var numList = from listOfNumList in listOfNumLists 
                          from value in listOfNumList 
                          select value; 
            
            Console.WriteLine("Numbers in the list:"); 
            foreach (var num in numList) { 
                Console.WriteLine(num); 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Output

Numbers in the list: 1 2 3 4

Các biến thể và mở rộng

1. SelectMany với index

var result = listOfNumLists.SelectMany((list, index) => 
    list.Select(item => new { Index = index, Value = item }));

2. Flatten List của Objects

public class Department {
    public string Name { get; set; }
    public List Employees { get; set; }
}

var allEmployees = departments.SelectMany(d => d.Employees);

3. Flatten với điều kiện (Where)

var evenNumbers = listOfNumLists.SelectMany(x => x).Where(x => x % 2 == 0);

4. SelectMany vs Select

// Select: trả về IEnumerable> (nested)
var nested = listOfNumLists.Select(x => x); 

// SelectMany: trả về IEnumerable (flattened)
var flat = listOfNumLists.SelectMany(x => x);

5. Aggregate / String.Join (alternative)

// Chỉ để hiển thị, không tạo list mới
string joined = string.Join(", ", listOfNumLists.SelectMany(x => x));

6. Chuyển thành List<T> cụ thể

List flatList = listOfNumLists.SelectMany(x => x).ToList();

Performance Note

  • SelectMany deferred execution - chỉ thực thi khi enumerate
  • ToList() materializes ngay lập tức
  • Với list lớn, cân nhắc memory usage