持续更新的.NET实用扩展方法,具体内容如下
1. 字符串转换为可空数值类型(int, long, float...类似)
/// <summary> /// 将字符串转换成32位整数,转换失败返回null /// </summary> /// <param name="str">转换的字符串</param> /// <returns>转换之后的整数,或null</returns> public static int? TryParseToInt32(this string str) { if (string.IsNullOrWhiteSpace(str)) return null; var result = 0; if (int.TryParse(str, out result)) return result; else return null; }
2. 去除子字符串
/// <summary> /// 去除子字符串 /// </summary> /// <param name="str">原字符串</param> /// <param name="substring">要去除的字符串</param> /// <returns>去除子字符串之后的结果</returns> public static string DeSubstring(this string str, string substring) { if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(substring) || !str.Contains(substring)) { return str; } return Regex.Replace(str, Regex.Escape(substring), string.Empty); } /// <summary> /// 去除子字符串 /// </summary> /// <param name="str">原字符串</param> /// <param name="substrings">要去除的子字符串</param> /// <returns>去除子字符串之后的结果</returns> public static string DeSubstring(this string str, params string[] substrings) { if (string.IsNullOrEmpty(str)) return str; if (substrings == null) return str; var newStr = str; foreach (var item in substrings) { newStr = newStr.DeSubstring(item); } return newStr; }
3. 获取子序列
/// <summary> /// 获取子序列 /// </summary> /// <typeparam name="T">序列中元素类型</typeparam> /// <param name="source">源数据</param> /// <param name="startIndex">开始索引(返回时包括)</param> /// <param name="endIndex">结束索引(返回时包括)</param> /// <returns>子序列</returns> public static IEnumerable<T> SubEnumerable<T>(this IEnumerable<T> source, int startIndex, int endIndex) { if (source == null) yield return default(T); var length = source.Count(); if (startIndex < 0 || endIndex < startIndex || startIndex >= length || endIndex >= length) throw new ArgumentOutOfRangeException(); var index = -1; foreach (var item in source) { index++; if (index < startIndex) continue; if (index > endIndex) yield break; yield return item; } }
4. 通过指定键对序列去重, 不必实现IEqualityComparer接口
/// <summary> /// 通过对指定的值进行比较返回序列中的非重复元素。 /// </summary> /// <typeparam name="T">序列中元素类型</typeparam> /// <typeparam name="TResult">指定的比较属性类型</typeparam> /// <param name="source">源数据</param> /// <param name="selector">应用于每个元素的转换函数</param> /// <returns>一个包含源序列中的按指定属性非重复元素</returns> public static IEnumerable<T> Distinct<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); var set = new HashSet<TResult>(); foreach (var item in source) { var result = selector(item); if (set.Add(result)) { yield return item; } } }
新闻热点
疑难解答
图片精选