C#-Linq源码解析之Any

前言

在Dotnet开发过程中,Any作为IEnumerable的扩展方法,十分常用。本文对Any方法的关键源码进行简要分析,以方便大家日后更好的使用该方法。.

使用

Any 确定序列中是否包含元素或存在元素满足指定条件。

看这样一个例子,我们判断集合中是否存在元素

List<UserInforMation> lstUserInforMations = new List<UserInforMation>();
bool flag = lstUserInforMations.Any();
flag= lstUserInforMations.Any(o=>o.Sex=="男");

当然flag都为false。

我们现在给集合赋值

//赋值
lstUserInforMations = new List<UserInforMation> 
{
   new UserInforMation{UserName="张三",Sex="男"},
   new UserInforMation{UserName="李四",Sex="女"},
};
flag = lstUserInforMations.Any();
flag = lstUserInforMations.Any(o => o.Sex == "男");

只要有一个条件满足,当然就会返回true了

源码解析

第一个方法

public static bool Any<TSource>(this IEnumerable<TSource> source)
参数
  • source 元素的类型
返回值
  • bool

该方法表示 只要有一个元素存在就返回True,否则返回false。

IEnumerable修饰我们的源元素类型,那么我们就知道源元素是一个 可以获得循环访问集合的枚举器那么我们就可以使用GetEnumerator这个方法进行迭代了。

然后我们在使用MoveNext方法,来遍历集合的元素!

源码:
 public static bool Any<TSource>(this IEnumerable<TSource> source)
{
  if (source == null)
  {
     throw null;
  }

  using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
   if (enumerator.MoveNext())
   {
     eturn true;
   }
 }

return false;
}

第二个方法

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
参数
  • source 元素的类型
  • Func<TSource, bool> predicate 该委托用于判断某元素是否满足某个条件,这个func委托接收一个和源元素相同的参数类型,并返回一个bool!
返回值
  • bool

我们在第一个方法上改进,使用foreach遍历源元素,如果有一个满足我们就返回true

源码:
  public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
 {
            if (source == null)
            {
                throw null;
            }

            if (predicate == null)
            {
                throw null;
            }

            foreach (TSource item in source)
            {
                if (predicate(item))
                {
                    return true;
                }
            }

            return false;
}

总结

在我们了解了any的源码后,我们在判断集合为空的时候是不是使用Any() 比Count() 更好一点了呢?欢迎留言讨论