C# Linq TakeWhile() 方法


使用 TakeWhile() 方法,只要序列中條件為真,就可以獲取元素。

以下是我們帶有字串的列表。

IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};

現在,假設我們需要長度小於 4 的字串。為此,請使用 Lambda 表示式,並將其作為條件新增到 TakeWhile() 方法中。

str.TakeWhile(a => a.Length < 4);

以下示例顯示了在條件為真時顯示元素。

示例

 現場演示

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
      var res = str.TakeWhile(a => a.Length < 4);
      foreach(var arr in res)
      Console.WriteLine(arr);
   }
}

輸出

Car
Bus

更新於: 23-6-2020

580 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.