扩展方法判断序列(或集合)是否包含元素

自定义扩展方法:

 public static class EnumerableExtensions
    {
        public static bool IsEmpty<T>(this IEnumerable<T> source)
        {
            return !source.Any();
        }
        public static bool IsNotEmpty<T>(this IEnumerable<T> source)
        {
            return source.Any();
        }
    }

 

测试用到的Person类:

public class Person
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        
    }

mian函数:

 static void Main(string[] args)
        {
            List<Person> list = new List<Person>() 
            {
                new Person{Id=1,Name="张三"},
                new Person{Id=2,Name="李四"},
            };
            if (list.IsNotEmpty())
            {
               Console.WriteLine("not empty");
            }
            else
            {
                Console.WriteLine("empty");
            }
            Console.ReadKey();
        }


运行截图:

 

总结:其实只是对linq中的Any()方法进行了一下简单的封装。

用source.Any()方法比用source.Count()>0较好,是因为source.Count()>0 遇到 yeild return等情况时会出现性能问题。

简言之,用source.Any()方法比较高效和保险。

而source.Any()的名字没IsEmpty和IsNotEmpty通俗易懂(好听),故,用扩展方法封装了一下。

posted @ 2015-06-14 16:36  秋刀鱼No1  阅读(158)  评论(0编辑  收藏  举报