开放的编程资料库

当前位置:我爱分享网 > C#教程 > 正文

C# 列表包含和存在

在这篇文章中,我们展示了如何在C#中检查一个元素或特定元素是否在列表中。

C#列表是相同类型元素的集合。可以通过索引访问元素。

检查列表中一个或多个元素是否存在的两种基本方法是:ContainsExists

或者,也可以使用CountIndexOfFindAny方法。

C#列表包含

Contains方法检查列表中是否存在元素。

public bool Contains (T item);

该方法返回一个布尔值。

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#列表存在

Exists方法确定列表是否包含与指定谓词匹配的元素。

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方法。一个计算所有元素,另一个计算所有匹配条件的元素。

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。

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#教程。

未经允许不得转载:我爱分享网 » C# 列表包含和存在

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏