C# List Contains & Exists
最后修改于 2023 年 7 月 5 日
在本文中,我们将展示如何在 C# 中检查列表中是否存在元素或特定元素。
C# 列表是相同类型元素的集合。 可以通过索引访问这些元素。
检查列表中元素或元素存在性的两个基本方法是:Contains 和 Exists。
或者,也可以使用 Count、IndexOf、Find 或 Any 方法。
C# List Contains
Contains 方法检查列表中是否存在某个元素。
public bool Contains (T item);
该方法返回一个布尔值。
Program.cs
var words = new List<string> { "falcon", "water", "war", "pen", "ocean" };
var w1 = "war";
var w2 = "cup";
if (words.Contains(w1))
{
Console.WriteLine($"{w1} is in the list");
}
else
{
Console.WriteLine($"{w1} is not in the list");
}
if (words.Contains(w2))
{
Console.WriteLine($"{w2} is in the list");
}
else
{
Console.WriteLine($"{w2} is not in the list");
}
在该示例中,我们检查两个单词是否存在于定义的单词列表中。
$ dotnet run war is in the list cup is not in the list
C# List Exists
Exists 方法确定列表是否包含与指定谓词匹配的元素。
Program.cs
var words = new List<string> { "falcon", "water", "war", "pen", "ocean" };
bool res = words.Exists(e => e.StartsWith("w"));
if (res)
{
Console.WriteLine("There are words starting in w");
} else
{
Console.WriteLine("There are no words starting in w");
}
bool res2 = words.Exists(e => e.EndsWith("c"));
if (res2)
{
Console.WriteLine("There are words ending in c");
} else
{
Console.WriteLine("There are no words ending in c");
}
在该程序中,我们检查是否存在一些以“w”开头并以“c”结尾的单词;
bool res = words.Exists(e => e.StartsWith("w"));
Exists 方法接受一个谓词函数作为参数。 谓词采用 lambda 表达式的形式。
if (res)
{
Console.WriteLine("There are words starting in w");
} else
{
Console.WriteLine("There are no words starting in w");
}
根据接收到的值打印消息。
$ dotnet run There are words starting in w There are no words ending in c
C# Enumerable.Count
我们可以使用 LINQ 的 Count 检查列表中是否存在一个或多个元素。 Count 方法返回序列中元素的数量。
有两个重载的 Count 方法。 一个计算所有元素,另一个计算所有符合条件的元素。
Program.cs
var vals = new List<int> { -2, 0, -1, 4, 3, 5, 3, 8 };
int n = vals.Count(e => e < 0);
if (n == 0)
{
Console.WriteLine("There are no negative values");
} else
{
Console.WriteLine($"There are {n} negative values");
}
在该程序中,我们使用 Count 检查列表中是否存在负值。
int n = vals.Count(e => e < 0);
我们使用将谓词作为参数的方法。
$ dotnet run There are 2 negative values
C# Enumerable.Any
Any 方法确定序列中是否存在任何元素或满足条件。 它返回一个布尔值 true 或 false。
Program.cs
var vals = new List<int> { -2, 0, -1, 4, 3, 5, 3, 8 };
bool r = vals.Any(e => e < 0);
if (r)
{
Console.WriteLine("There are negative values");
} else
{
Console.WriteLine($"There are no negative values");
}
在该程序中,我们使用 Any 检查是否存在一些负值。
$ dotnet run There are negative values
来源
在本文中,我们展示了如何在 C# 中检查列表中是否存在元素。
作者
列出所有 C# 教程。