常用扩展方法-1


1. 什么扩展方法

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种静态方法,但可以像扩展类型上的实例方法一样进行调用。 对于用 C#、F# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中定义的方法没有明显区别。


2. 使用扩展方法

2-1. 创建Employee类并写入数据

在使用之前,我们先创建初始数据。首先创建Employee类,代码如下:

class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public bool Gender { get; set; }
    public int Salary { get; set; }
    public override string ToString()
    {
        return $"ID={Id},Name={Name},Age={Age},Gender={Gender},Salary={Salary}";
    }
}

之后对Employee类写入数据,代码如下:

List<Employee> list = new List<Employee>();
list.Add(new Employee { Id = 1, Name = "jerry", Age = 28, Gender = true, Salary = 5000 });
list.Add(new Employee { Id = 2, Name = "jim", Age = 33, Gender = true, Salary = 3000 });
list.Add(new Employee { Id = 3, Name = "lily", Age = 35, Gender = false, Salary = 9000 });
list.Add(new Employee { Id = 4, Name = "lucy", Age = 16, Gender = false, Salary = 2000 });
list.Add(new Employee { Id = 5, Name = "kimi", Age = 25, Gender = true, Salary = 1000 });
list.Add(new Employee { Id = 6, Name = "nancy", Age = 35, Gender = false, Salary = 8000 });
list.Add(new Employee { Id = 7, Name = "zack", Age = 35, Gender = true, Salary = 8500 });
list.Add(new Employee { Id = 8, Name = "jack", Age = 33, Gender = true, Salary = 8000 });

2-2. 使用扩展方法

  1. Where()方法: Where方法的定义:按照条件筛选数据
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

其中参数this IEnumerable<TSource> source是Where方法需要处理的数据,参数Func<TSource, bool> predicate是一个泛型委托,它的参数是集合的数据类型,返回值是一个布尔类型,表达当前数据是否符合过滤条件predicate。现在我们使用Where方法来查找年龄大于30的员工,代码如下:

list.Where(e => e.Age > 30);

并且该的代码返回的是IEnumerable<Employee>类型,所以我们可以使用foreach来对结果进行显示,代码如下:

foreach (var item in result)
{
    Console.WriteLine(item);
}
  1. Count()方法 Count方法的定义:获取符合条件的数据的个数
public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

Count方法也有不含筛选条件的重载,来获取数据的总数。

public static int Count<TSource>(this IEnumerable<TSource> source)

注意!List或Dictionary等的Count属性和Count()方法是不同,要注意区分。 与Where方法相同,Count方法中的两个参数一个是需要处理的数据,另一个则是被筛选的数据需要满足的条件。

  1. Any()方法 Any方法的定义:数据中是否存在符合条件的数据
 public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

Any方法同样存在不含筛选条件的重载,使用它可以用来判断传入的集合是否含有数据。

 public static bool Any<TSource>(this IEnumerable<TSource> source)

与Count相比,如果仅仅想要判断集合中是否有满足条件的数据,使用Any方法会更有效率。因为当条件满足是,Any方法会直接返回,而Count方法则会将所有数据全部进行判断


3.总结

方法 作用 返回值
Where 按照条件筛选数据 IEnumerable类型
Count 获取符合条件的数据的个数 int类型
Any 数据中是否存在符合条件的数据 bool类型

本文章使用limfx的vscode插件快速发布