判断List是否包含元素常用Contains方法,适用于简单类型;自定义对象需重写Equals和GetHashCode;复杂条件推荐使用LINQ的Any方法。

在 C# 中,判断一个 List 是否包含某个元素,最常用的方法是使用 Contains 方法。该方法返回一个布尔值,表示列表中是否存在指定元素。
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
bool hasThree = numbers.Contains(3);
Console.WriteLine(hasThree); // 输出: True
<p>List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
bool hasAlice = names.Contains("Alice");
Console.WriteLine(hasAlice); // 输出: True
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">public override bool Equals(object obj)
{
if (obj is Person other)
return Name == other.Name && Age == other.Age;
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}}
// 使用示例 List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 } };
Person search = new Person { Name = "Alice", Age = 30 }; bool contains = people.Contains(search); Console.WriteLine(contains); // 输出: True
using System.Linq;
<p>List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 }
};</p><p>bool hasAdult = people.Any(p => p.Age >= 18);
Console.WriteLine(hasAdult); // 输出: True</p><p>bool hasAlice = people.Any(p => p.Name == "Alice");
Console.WriteLine(hasAlice); // 输出: True
Contains 更适合精确值匹配,而 Any 提供了更大的灵活性,支持复杂条件判断。
基本上就这些。根据你的数据类型和需求选择合适的方式即可。
以上就是C# 如何判断一个 List 是否包含某个元素_C# List 元素包含判断方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号