using JNPF.DependencyInjection; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JNPF.Common.Extension; /// /// Enumerable集合扩展方法. /// [SuppressSniffer] public static class EnumerableExtensions { /// /// 将集合展开并分别转换成字符串,再以指定的分隔符衔接,拼成一个字符串返回。默认分隔符为逗号. /// /// 要处理的集合. /// 分隔符,默认为逗号. /// 拼接后的字符串. public static string ExpandAndToString(this IEnumerable collection, string separator = ",") { return collection.ExpandAndToString(item => item?.ToString() ?? string.Empty, separator); } /// /// 循环集合的每一项,调用委托生成字符串,返回合并后的字符串。默认分隔符为逗号. /// /// 待处理的集合. /// 单个集合项的转换委托. /// 分隔符,默认为逗号. /// 泛型类型. /// public static string ExpandAndToString(this IEnumerable collection, Func itemFormatFunc, string separator = ",") { collection = collection as IList ?? collection.ToList(); if (!collection.Any()) { return string.Empty; } StringBuilder sb = new StringBuilder(); int i = 0; int count = collection.Count(); foreach (T item in collection) { if (i == count - 1) { sb.Append(itemFormatFunc(item)); } else { sb.Append(itemFormatFunc(item) + separator); } i++; } return sb.ToString(); } /// /// 集合是否为空. /// /// 要处理的集合. /// 动态类型. /// 为空返回True,不为空返回False. public static bool IsEmpty(this IEnumerable collection) { collection = collection as IList ?? collection.ToList(); return !collection.Any(); } /// /// Contains扩展 /// added by ly on 20230814 /// /// /// /// /// public static bool In(this T obj, IEnumerable collection) { var result = false; foreach (var item in collection) { result |= item.Equals(obj); } return result; } /// /// 连接为字符串 /// /// /// /// public static string JoinAsString(this IEnumerable source, string separator) { return string.Join(separator, source); } }