EnumerableExtensions.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using System.Collections.Concurrent;
  2. namespace MeloongCore.Extensions;
  3. public static class EnumerableExtensions {
  4. #region 去重
  5. /// <summary>
  6. /// 通过比较器进行去重。
  7. /// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
  8. /// </summary>
  9. public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
  10. var seen = new List<T>();
  11. foreach (var item in list) {
  12. if (!seen.Any(s => comparer(s, item))) {
  13. seen.Add(item);
  14. yield return item;
  15. }
  16. }
  17. }
  18. /// <summary>
  19. /// 按对象的指定值去重。
  20. /// </summary>
  21. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) {
  22. var seen = new HashSet<TKey>();
  23. foreach (var element in source) {
  24. if (seen.Add(selector(element))) yield return element;
  25. }
  26. }
  27. /// <summary>
  28. /// 按对象的指定值去重。
  29. /// </summary>
  30. public static ParallelQuery<TSource> DistinctBy<TSource, TKey>(this ParallelQuery<TSource> source, Func<TSource, TKey> selector) {
  31. var seen = new ConcurrentDictionary<TKey, bool>();
  32. return source.Where(element => seen.TryAdd(selector(element), true));
  33. }
  34. #endregion
  35. #region 最大 / 最小
  36. /// <summary>
  37. /// 选择所有最大值对应的对象。
  38. /// 若没有元素则返回空列表。
  39. /// </summary>
  40. public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
  41. var results = new List<TSource>();
  42. using var enumerator = source.GetEnumerator();
  43. if (!enumerator.MoveNext()) return results;
  44. TSource maxItem = enumerator.Current;
  45. TKey maxValue = selector(maxItem);
  46. results.Add(maxItem);
  47. while (enumerator.MoveNext()) {
  48. TSource currentItem = enumerator.Current;
  49. TKey currentValue = selector(currentItem);
  50. int comparisonResult = currentValue.CompareTo(maxValue);
  51. if (comparisonResult > 0) {
  52. maxValue = currentValue;
  53. results.Clear();
  54. results.Add(currentItem);
  55. } else if (comparisonResult == 0) {
  56. results.Add(currentItem);
  57. }
  58. }
  59. return results;
  60. }
  61. /// <summary>
  62. /// 选择所有最小值对应的对象。
  63. /// 若没有元素则返回空列表。
  64. /// </summary>
  65. public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
  66. var results = new List<TSource>();
  67. using var enumerator = source.GetEnumerator();
  68. if (!enumerator.MoveNext()) return results;
  69. TSource minItem = enumerator.Current;
  70. TKey minValue = selector(minItem);
  71. results.Add(minItem);
  72. while (enumerator.MoveNext()) {
  73. TSource currentItem = enumerator.Current;
  74. TKey currentValue = selector(currentItem);
  75. int comparisonResult = currentValue.CompareTo(minValue);
  76. if (comparisonResult < 0) {
  77. minValue = currentValue;
  78. results.Clear();
  79. results.Add(currentItem);
  80. } else if (comparisonResult == 0) {
  81. results.Add(currentItem);
  82. }
  83. }
  84. return results;
  85. }
  86. /// <summary>
  87. /// 选择最大值对应的对象。
  88. /// 若没有元素则返回 null。
  89. /// </summary>
  90. public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
  91. using var enumerator = source.GetEnumerator();
  92. if (!enumerator.MoveNext()) return default;
  93. TSource maxItem = enumerator.Current;
  94. TKey maxValue = selector(maxItem);
  95. while (enumerator.MoveNext()) {
  96. TKey value = selector(enumerator.Current);
  97. if (value.CompareTo(maxValue) <= 0) continue;
  98. maxItem = enumerator.Current;
  99. maxValue = value;
  100. }
  101. return maxItem;
  102. }
  103. /// <summary>
  104. /// 选择最小值对应的对象。
  105. /// 若没有元素则返回 null。
  106. /// </summary>
  107. public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
  108. using var enumerator = source.GetEnumerator();
  109. if (!enumerator.MoveNext()) { return default; }
  110. TSource minItem = enumerator.Current;
  111. TKey minValue = selector(minItem);
  112. while (enumerator.MoveNext()) {
  113. TKey value = selector(enumerator.Current);
  114. if (value.CompareTo(minValue) >= 0) { continue; }
  115. minItem = enumerator.Current;
  116. minValue = value;
  117. }
  118. return minItem;
  119. }
  120. #endregion
  121. #region 排序
  122. /// <summary>
  123. /// 使用默认比较器对集合进行排序。顺序为从小到大。
  124. /// </summary>
  125. public static IEnumerable<T> Ordered<T>(this IEnumerable<T> source) where T : IComparable<T>
  126. => source.OrderBy(x => x);
  127. /// <summary>
  128. /// 使用默认比较器对集合进行排序。顺序为从大到小。
  129. /// </summary>
  130. public static IEnumerable<T> OrderedDescending<T>(this IEnumerable<T> source) where T : IComparable<T>
  131. => source.OrderByDescending(x => x);
  132. #endregion
  133. #region Join
  134. /// <summary>
  135. /// 用指定的分割符将集合连接为字符串。
  136. /// </summary>
  137. public static string Join(this IEnumerable list, char split) {
  138. var builder = new StringBuilder();
  139. bool isFirst = true;
  140. foreach (var element in list) {
  141. if (isFirst)
  142. isFirst = false;
  143. else
  144. builder.Append(split);
  145. if (element is not null) builder.Append(element.ToString());
  146. }
  147. return builder.ToString();
  148. }
  149. /// <summary>
  150. /// 用指定的分割符将集合连接为字符串。
  151. /// </summary>
  152. public static string Join(this IEnumerable list, string split) {
  153. if (split.IsSingle()) return list.Join(split[0]);
  154. var builder = new StringBuilder();
  155. bool isFirst = true;
  156. foreach (var element in list) {
  157. if (isFirst)
  158. isFirst = false;
  159. else
  160. builder.Append(split);
  161. if (element is not null) builder.Append(element.ToString());
  162. }
  163. return builder.ToString();
  164. }
  165. #endregion
  166. #region Dictionary
  167. /// <summary>
  168. /// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
  169. /// 返回是否确实移除了元素。
  170. /// </summary>
  171. public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key)
  172. => dict.TryRemove(key, out _);
  173. /// <summary>
  174. /// 将二维数组转换为字典。
  175. /// </summary>
  176. public static Dictionary<T, T> ToDictionary<T>(this T[,] arr) where T : notnull {
  177. Dictionary<T, T> result = [];
  178. if (arr.Length == 0) return result;
  179. if (arr.GetLength(1) != 2) throw new ArgumentException("数组必须为两列,第一列为 Key,第二列为 Value。");
  180. for (int i = 0; i < arr.GetLength(0); i++) result[arr[i, 0]] = arr[i, 1];
  181. return result;
  182. }
  183. /// <summary>
  184. /// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
  185. /// </summary>
  186. public static TValue? GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue? defaultValue = default)
  187. => dict.TryGetValue(key, out var result) ? result : defaultValue;
  188. /// <summary>
  189. /// 将值添加到字典的对应项的列表中。
  190. /// </summary>
  191. public static void AddIntoValueCollection<TKey, TValue>(this IDictionary<TKey, List<TValue>> dict, TKey key, TValue value) {
  192. if (dict.TryGetValue(key, out var collection)) {
  193. collection.Add(value);
  194. } else {
  195. dict.Add(key, [value]);
  196. }
  197. }
  198. #endregion
  199. /// <summary>
  200. /// 将 <see cref="FlagsAttribute"/> 枚举值解包为它包含的单一 Flag 成员的集合。
  201. /// 建议仅对没有极端值的正数枚举使用。
  202. /// </summary>
  203. /// <remarks>
  204. /// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
  205. /// </remarks>
  206. public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum
  207. => EnumUtils.GetAllFlags<T>().Where(element => value.HasFlag(element));
  208. /// <summary>
  209. /// 从集合中移除满足条件的元素。
  210. /// </summary>
  211. public static void RemoveIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
  212. var itemsToRemove = source.Where(predicate).ToList();
  213. foreach (var item in itemsToRemove) source.Remove(item);
  214. }
  215. /// <summary>
  216. /// 仅保留满足条件的元素,移除不满足条件的元素。
  217. /// </summary>
  218. public static void KeepIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
  219. var itemsToRemove = source.Where(item => !predicate(item)).ToList();
  220. foreach (var item in itemsToRemove) source.Remove(item);
  221. }
  222. /// <summary>
  223. /// 判断集合是否有且仅有一个元素。
  224. /// 在输入 null 时返回 false。
  225. /// </summary>
  226. public static bool IsSingle<T>(this IEnumerable<T>? source) {
  227. if (source is null) return false;
  228. if (source is IList<T> list) return list.Count == 1;
  229. using var enumerator = source.GetEnumerator();
  230. if (!enumerator.MoveNext()) return false;
  231. if (enumerator.MoveNext()) return false;
  232. return true;
  233. }
  234. /// <summary>
  235. /// 对集合的每个元素执行指定操作。
  236. /// </summary>
  237. public static IEnumerable<T> ForAll<T>(this IEnumerable<T> source, Action<T> action) {
  238. foreach (T item in source) action(item);
  239. return source;
  240. }
  241. }