C# Linq TakeWhile() 方法

csharpprogrammingserver side programming更新于 2025/9/14 11:19:00

使用 TakeWhile() 方法按顺序获取条件为真的元素。

以下是包含字符串的列表。

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

现在,假设我们需要长度小于 4 的字符串。为此,使用 Lambda 表达式并将其作为条件添加到 TakeWhile() 方法中。

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

以下是显示元素直到条件为 trie 的示例。

示例

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

相关文章