📅  最后修改于: 2023-12-03 15:40:33.773000             🧑  作者: Mango
在程序中,我们经常需要检查一个对象列表是否包含某个特定的值。这个过程在 C# 和 TypeScript 中是非常相似的。其中,C# 可以使用 Contains()
方法进行检查,而 TypeScript 则可以使用 includes()
方法。
在 C# 中,我们可以使用 List 类型的 Contains()
方法来检查一个对象列表是否包含特定的值。下面是一个简单的示例:
List<string> fruits = new List<string> { "apple", "banana", "orange" };
string fruit = "banana";
if (fruits.Contains(fruit))
{
Console.WriteLine($"{fruit} is in the list.");
}
else
{
Console.WriteLine($"{fruit} is not in the list.");
}
上面的代码会输出:
banana is in the list.
在 TypeScript 中,我们可以使用 Array 类型的 includes()
方法来检查一个对象列表是否包含特定的值。下面是一个简单的示例:
let fruits: string[] = ["apple", "banana", "orange"];
let fruit: string = "banana";
if (fruits.includes(fruit))
{
console.log(`${fruit} is in the list.`);
}
else
{
console.log(`${fruit} is not in the list.`);
}
上面的代码会输出:
banana is in the list.
以上就是检查对象列表是否包含特定值的方法,在 C# 中使用 Contains()
方法,在 TypeScript 中使用 includes()
方法。无论是在 C# 还是 TypeScript 中,这些方法都非常方便实用。