📌  相关文章
📜  使用 LINQ 检查列表集合中是否存在指定城市的 C# 程序(1)

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

使用 LINQ 检查列表集合中是否存在指定城市的 C# 程序

在 C# 中,我们可以使用 LINQ 查询语句来检查一个列表集合(List)中是否存在指定城市。这里我们假设列表集合中的每个元素都是一个包含了城市名字的字符串。

List<string> cities = new List<string>{"New York", "London", "Paris", "Tokyo"};

bool cityExists = cities.Any(city => city == "London");

if (cityExists)
{
    Console.WriteLine("London exists in the list!");
}
else
{
    Console.WriteLine("London does not exist in the list.");
}

上面的代码中,我们首先定义了一个字符串列表 cities,包含了四个城市的名字。接着,我们使用 LINQ 的 Any() 方法来检查列表中是否存在名字为 London 的城市。Any() 方法接收一个 Lambda 表达式作为参数,表示用来判断元素是否符合条件的委托。在这里,我们判断城市名字是否等于 "London"。最后,我们根据 cityExists 的值输出相应的结果。

以下是上述程序的 markdown 版本代码片段:

```csharp
List<string> cities = new List<string>{"New York", "London", "Paris", "Tokyo"};

bool cityExists = cities.Any(city => city == "London");

if (cityExists)
{
    Console.WriteLine("London exists in the list!");
}
else
{
    Console.WriteLine("London does not exist in the list.");
}