Метод Exists
Метод Exists класса List<T>
принимает предикат и возвращает true,
если хотя бы один элемент удовлетворяет условию.
Синтаксис
bool found = list.Exists(match);
Пример
Давайте проверим, есть ли число больше 4:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
Console.WriteLine(nums.Exists(x => x > 4));
}
}
Результат выполнения кода:
True
Пример
Давайте получим False для ложного условия:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
Console.WriteLine(nums.Exists(x => x > 10));
}
}
Результат выполнения кода:
False
Пример
Давайте проверим строки:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> items = new List<string> {"a", "b", "c", "d", "e"};
Console.WriteLine(items.Exists(s => s == "d"));
}
}
Результат выполнения кода:
True
Пример
Давайте сравним с TrueForAll:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
Console.WriteLine(nums.TrueForAll(x => x > 0));
}
}
Результат выполнения кода:
True
Смотрите также
-
метод
TrueForAll,
который проверяет условие на каждом -
метод
Find,
который возвращает найденный элемент -
метод
Contains,
который проверяет конкретное значение -
метод
FindAll,
который собирает все подходящие