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

解决方案 »

  1.   

    在行为上,其两个没有区别,相同的.
    只是 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)) { }
            }
        }
    }
      

  2.   

    以下是老外的解释:
    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.