LINQ中的Contains和Any有什么区别?

LINQ中的ContainsAny什么区别?

Contains一个对象, Any采用谓词。

您使用像这样的Contains

 listOFInts.Contains(1); 

Any这样的:

 listOfInts.Any(i => i == 1); listOfInts.Any(i => i % 2 == 0); // Check if any element is an Even Number 

因此,如果要检查特定条件,请使用Any 。 如果要检查元素是否存在,请使用“ Contains

MSDN for Contains , Any

如果序列包含指定的元素,则Contains检查。

Enumerable.Any检查序列的元素是否满足条件。

请考虑以下示例:

 List list = new List { 1, 2, 3, 4, 5 }; bool contains = list.Contains(1); //true bool condition = list.Any(r => r > 2 && r < 5); 

包含关于源集合是否为ICollection的关注,Any不关心。

Enumerable.Any http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#6a1af7c3d17845e3

 public static bool Any(this IEnumerable source, Func predicate) { foreach (TSource local in source) { if (predicate(local)) { return true; } } return false; } 

Enumerable.Contains http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#f60bab4c5e27a849

 public static bool Contains(this IEnumerable source, TSource value) { ICollection collection = source as ICollection; if (collection != null) { return collection.Contains(value); } return source.Contains(value, null); } 

包含

使用默认的相等比较器确定序列是否包含指定的元素。

任何

确定序列是否包含任何元素。

至于文件:

似乎无法找到任何关于它的文档。

所有(大多数?)LINQ扩展方法: 这里