如何在 C# 中根據謂詞指定條件獲取一個 List 中所有滿足條件的元素?
要獲取一個 List 中滿足謂詞指定條件的所有元素,程式碼如下 −
示例
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 3) == 0);
}
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(9);
list.Add(15);
list.Add(20);
list.Add(40);
list.Add(50);
list.Add(60);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
List<int> res = new List<int>(list.FindAll(demo));
Console.WriteLine("List that match the conditions...");
foreach (int i in res) {
Console.WriteLine(i);
}
}
}輸出
這將產生以下輸出 −
List elements... 9 15 20 40 50 60 List that match the conditions... 9 15 60
示例
讓我們看另一個示例 −
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 100) == 5);
}
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(900);
list.Add(1500);
list.Add(250);
list.Add(405);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
List<int> res = new List<int>(list.FindAll(demo));
Console.WriteLine("List that match the conditions...");
foreach (int i in res) {
Console.WriteLine(i);
}
}
}輸出
這將產生以下輸出 −
List elements... 900 1500 250 405 List that match the conditions... 405
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP