如何使用 LINQ C# 展平列表?


展平列表是指將 List<List<T>> 轉換為 List<T>。例如,讓我們考慮一個 List<List<int>>,需要將其轉換為 List<int>。

LINQ 中的 SelectMany 用於將序列的每個元素投影到 IEnumerable<T> 中,然後將結果序列展平為一個序列。這意味著 SelectMany 運算子將結果序列中的記錄合併,然後將其轉換為一個結果。

使用 SelectMany

示例

 線上演示

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();
      }
   }
}

輸出

Numbers in the list:
1
2
3
4

使用查詢

示例

 線上演示

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();
      }
   }
}

輸出

Numbers in the list:
1
2
3
4

更新時間: 2020-9-24

6K+ 檢視

開啟你的 職業

透過完成課程取得認證

開始
廣告