您的位置:首页 > 其它

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

2015-06-14 16:36 381 查看
自定义扩展方法:

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通俗易懂(好听),故,用扩展方法封装了一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: