📜  c# list any retun indec - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.331000             🧑  作者: Mango

C# List.Any 返回索引

在 C# 中,List.Any 方法可用于检查列表中是否包含符合特定条件的元素。有时候,我们希望能够找到列表中符合条件的元素的索引,本文将介绍如何使用 List.Any 方法来实现这一目的。

List.Any 方法

List.Any() 方法用于检查列表中是否存在符合指定条件的元素,如果存在,则返回 true,否则返回 false。

List.Any() 方法有两种重载方法:

bool Any();
bool Any(Func<T, bool> predicate);

第一种重载方法用于检查列表中是否包含元素,即使没有指定条件。第二种重载方法则需要指定一个条件,用于判断列表中的元素是否符合该条件。

返回符合条件的元素的索引

虽然 List.Any() 方法只返回 true 或 false,但我们可以使用另一个方法 List.FindIndex() 来找到符合条件的元素的索引。List.FindIndex() 方法需要一个谓词作为参数,它会在列表中查找符合该谓词的第一个元素,并返回该元素的索引。如果没有符合条件的元素,则返回 -1。

以下是一个示例代码:

List<int> numbers = new List<int>() { 2, 4, 6, 8, 10 };
int index = numbers.FindIndex(x => x % 2 == 1);
if (index != -1)
{
    Console.WriteLine($"第一个奇数的索引是: {index}");
}
else
{
    Console.WriteLine("该列表中没有奇数");
}

在以上示例代码中,我们查找了一个包含偶数的列表中,第一个奇数的索引。在谓词中,我们使用了取模运算符来判断该元素是否为奇数。最终输出的结果是:

该列表中没有奇数

如果我们将列表中的一个偶数修改为奇数,例如:

List<int> numbers = new List<int>() { 2, 5, 6, 8, 10 };
int index = numbers.FindIndex(x => x % 2 == 1);
if (index != -1)
{
    Console.WriteLine($"第一个奇数的索引是: {index}");
}
else
{
    Console.WriteLine("该列表中没有奇数");
}

则输出的结果应为:

第一个奇数的索引是: 1

以上就是使用 List.Any() 和 List.FindIndex() 方法来返回符合条件的元素的索引的示例介绍。