List对象的Any方法和Exists有什么区别?

zengjd 2010-01-27 11:48:55
List对象的Any方法和Exists有什么区别?
...全文
1117 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
鸭梨山大帝 2010-01-28
  • 打赏
  • 举报
回复
以下是老外的解释:
http://stackoverflow.com/questions/879391/linq-any-vs-exists-whats-the-difference

(我随便翻译的,呵呵)
List.Exists (Object method)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)
//Exists 是在LINQ之前,.net2.0的时候出现的,其用法就像调用委托,但是lambda expressions 为了办到向后兼容,仅仅只有List有该东东,而接口类ILIST是没有滴.

IEnumerable.Any (Extension method)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.
//Any 是在.NET 3.5 新增的,使用类似于 Func(TSource, bool),其可以被扩展用于Lambda表达式和Linq

In behaviour, these are identical.
zengjd 2010-01-28
  • 打赏
  • 举报
回复
非常感谢楼上的回答!
鸭梨山大帝 2010-01-28
  • 打赏
  • 举报
回复
在行为上,其两个没有区别,相同的.
只是 Exists 是 2.0的时候引入的,这是还没有Linq.
Any是3.5跟随Linq引入的
举例如下:没有using System.Linq的时候,X.any是会报错的

using System;
using System.Collections.Generic;
namespace ChangeIPAddress
{
class Program
{
static void Main()
{
List<int> x = new List<int>();
x.Add(1);
x.Add(2);
if (x.Exists(i => i == 0)) { }
}
}
}


而引入了之后就有了

using System;
using System.Collections.Generic;
using System.Linq;
namespace ChangeIPAddress
{
class Program
{
static void Main()
{
List<int> x = new List<int>();
x.Add(1);
x.Add(2);
if (x.Exists(i => i == 0)) { }
if (x.Any(i => i == 0)) { }
}
}
}
zengjd 2010-01-27
  • 打赏
  • 举报
回复
这么晚了,没人了?

110,548

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧