实用魔方块——数组运算基础
一、使用StringComparer匹配字符串中的字母大小
////// 【1】字符串数组,返回数组中字符串,字母最小的元素 /// /// 入参数组 /// public static string StringCompare(string[] s) { return s.OrderBy(a => a, StringComparer.Ordinal).First(); }
二、返回指定位数的数组元素
////// 【2】返回指定位数的数组元素 /// /// /// 需要取出的数字数量 /// public static int[] Take(int[] arr, int n) => arr.Take(n).ToArray();
三、生成指定位数的自然数数组,可指定起始位
////// 【3】自然数数组的生成(指定起始位和数量) /// /// /// /// public static int[] Between(int a, int b) { return Enumerable.Range(a, b).ToArray(); }
四、数组元素去重
////// 【4】数组元素去重 /// /// /// public static int[] distinct(int[] a) { return a.Distinct().ToArray(); }
五、判断另一数组是否包含当前数组元素
////// 【5】数组元素包含 /// /// /// /// public static bool Check(object[] a, object x) { return a.Contains(x); }
六、数组的倒序输出
////// 【6】数组倒序输出 /// /// public static string[] FixTheMeerkat(string[] arr) => arr.Reverse().ToArray();
七、数组元素最小值
//////【7】返回数组元素的最小值(可拓展为最大值) /// /// /// public static int FindSmallestInt(int[] args) { return args.Min(); }
八、判断数组是否为空
////// 【8】判断输入数组是否为空或null /// /// /// public static bool EmptyOrNull(int[] input) { return (input == null || !input.Any()) ? true : false; }
九、数组元素自运算求和
////// 【9】数组元素的运算(元素加2) /// /// /// public static int[] Maps(int[] x) { return x.Select(e => e * 2).ToArray(); }
十、数组的排序判断
////// 【10】判断数组是排序是顺序还是逆序 /// /// /// public static string IsSortedAndHow(int[] array) { if (array.OrderBy(a => a).SequenceEqual(array)) return "yes, ascending"; if (array.OrderByDescending(a => a).SequenceEqual(array)) return "yes, descending"; return "no"; }