一、三大函数概念(必考理解)
1. 高阶函数
参数是函数的函数,数组所有Find/Exists/ForEach 都是高阶函数。
2. 回调函数
以参数形式,传递给高阶函数的自定义函数(我们自己写的匹配方法)。
3. 递归函数
自己调用自己的函数(暂不讲解)。
二、普通查找的局限性
cs
int[] ages = { 20, 10, 30, 40, 50, 19, 21 };
Console.WriteLine(Array.IndexOf(ages, 20));
IndexOf 缺点 :只能精准匹配固定值,不能根据条件查询(不能查小于18、偶数、奇数等)。
👉 所以需要 数组高阶条件方法
三、Find 系列条件查询(静态方法)
工作原理(必背)
高阶函数自动循环遍历数组,每遍历一个元素就调用一次回调函数; 回调返回 true,立即返回当前元素;返回 false 继续遍历。
1. Array.Find() 查找【第一个满足条件的元素】
规则:找到返回元素值,找不到返回数据类型默认值(int默认0)
cs
// 找小于18的第一个元素
Console.WriteLine(Array.Find(ages, FindSmall18)); // 10
// 找第一个偶数
Console.WriteLine(Array.Find(ages, FindEven)); // 20
// 找第一个奇数
Console.WriteLine(Array.Find(ages, FindOdd)); // 19
// 找同时能被3和5整除的数
Console.WriteLine(Array.Find(ages, Find35)); // 30
2. Array.FindLast() 查找【最后一个满足条件的元素】
从后往前遍历,匹配第一个符合条件的元素
cs
Console.WriteLine(Array.FindLast(ages, Find35)); // 30
3. Array.FindAll() 查找【所有满足条件的元素】
返回值:新数组,存储所有符合条件的元素
cs
// 取出所有奇数
int[] arr = Array.FindAll(ages, FindOdd);
Console.WriteLine(string.Join("-", arr));
4. Array.FindIndex() 获取【第一个满足条件的索引】
cs
Console.WriteLine(Array.FindIndex(ages, FindEven)); // 0
5. Array.FindLastIndex() 获取【最后一个满足条件的索引】
cs
Console.WriteLine(Array.FindLastIndex(ages, FindEven)); // 4
四、数组遍历 & 条件判断方法
1. Array.ForEach() 高阶遍历
无需循环语句,通过回调函数遍历每一个元素(无返回值)
cs
Array.ForEach(ages, F1);
2. TrueForAll() 全部满足才为true
所有元素符合条件 → true;只要一个不满足 → false
cs
Console.WriteLine(Array.TrueForAll(arr, FindOdd));
3. Exists() 存在满足条件即为true
只要有一个元素满足条件 → true;全部不满足才是 false
cs
Console.WriteLine(Array.Exists(ages, Find35)); // true
五、数组拓展方法(非静态 / 实例方法)
需要通过数组实例调用,属于拓展方法
1. Count() 获取元素个数 等价于 Length
cs
Console.WriteLine(strs.Count());
2. All() 全部满足条件(等价 TrueForAll)
cs
Console.WriteLine(strs.All(F2));
3. Any() 存在满足条件(等价 Exists)
cs
Console.WriteLine(strs.Any(F2));
4. GetValue() 根据索引取值
cs
Console.WriteLine(strs.GetValue(0));
5. SetValue() 根据索引修改值
cs
strs.SetValue("郑爽", 0);
Console.WriteLine(strs.GetValue(0));
6. GetType() 获取对象类型、BaseType 获取父类类型
cs
Console.WriteLine(strs.GetType().BaseType.BaseType);
7. GetLength() 获取指定维度长度
cs
Console.WriteLine(strs.GetLength(0));
六、所有回调函数(完整汇总)
全部为 bool 返回值、单参数 匹配回调
cs
// 判断是否小于18
public static bool FindSmall18(int v)
{
return v < 18;
}
// 判断是否偶数
public static bool FindEven(int v)
{
return v % 2 == 0;
}
// 判断是否奇数
public static bool FindOdd(int v)
{
return v % 2 != 0;
}
// 判断能同时被3、5整除
public static bool Find35(int v)
{
return v % 3 == 0 && v % 5 == 0;
}
// 字符串长度是否为2
public static bool F2(string v)
{
return v.Length == 2;
}
// ForEach遍历回调(无返回值)
public static void F1(int v)
{
Console.WriteLine(v + "+++++++++++++++");
}
七、方法等价对照表
| 静态方法 Array | 实例拓展方法 | 作用 |
|---|---|---|
| TrueForAll | All | 全部满足返回true |
| Exists | Any | 存在满足返回true |
八、终极总结(背诵版)
-
高阶函数 :参数可以是方法;回调函数:当做参数传入的方法
-
IndexOf 只能查固定值,Find 系列可以按条件查询
-
Find:第一个元素;FindLast:最后一个元素;FindAll:所有元素(返回新数组)
-
FindIndex / FindLastIndex:获取条件匹配的索引
-
ForEach:高阶遍历,替代for循环
-
TrueForAll/All:全真才真;Exists/Any:一真即真
-
GetValue取值、SetValue改值,GetType获取类型