ref: 将 MeloongCore 的 WPF 部分独立到另一个子工程
This commit is contained in:
1 parent
1036bc9642
commit
1910e96567
13 files changed
+103
-29
No files matched your search
@@ -0,0 +1,236 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class EnumerableExtensions {
|
||||
|
||||
#region Distinct
|
||||
|
||||
/// <summary>
|
||||
/// 通过比较器进行去重。
|
||||
/// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
|
||||
for (int i = 0; i < list.Count; i++) {
|
||||
if (!list.Skip(i + 1).Any(item => comparer(list[i], item))) yield return list[i];
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 按对象的指定值去重。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) {
|
||||
var seen = new HashSet<TKey>();
|
||||
foreach (var element in source) {
|
||||
if (seen.Add(selector(element))) yield return element;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 按对象的指定值去重。
|
||||
/// </summary>
|
||||
public static ParallelQuery<T> DistinctBy<T, TKey>(this ParallelQuery<T> source, Func<T, TKey> selector) {
|
||||
var seen = new ConcurrentDictionary<TKey, bool>();
|
||||
return source.Where(element => seen.TryAdd(selector(element), true));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region MinBy / MaxBy
|
||||
|
||||
/// <summary>
|
||||
/// 选择所有最大值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TKey> MaxByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
var results = new List<TKey>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TKey maxItem = enumerator.Current;
|
||||
TValue maxValue = selector(maxItem);
|
||||
results.Add(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey currentItem = enumerator.Current;
|
||||
TValue currentValue = selector(currentItem);
|
||||
int comparisonResult = currentValue.CompareTo(maxValue);
|
||||
if (comparisonResult > 0) {
|
||||
maxValue = currentValue;
|
||||
results.Clear();
|
||||
results.Add(currentItem);
|
||||
} else if (comparisonResult == 0) {
|
||||
results.Add(currentItem);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择所有最小值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TKey> MinByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
var results = new List<TKey>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TKey minItem = enumerator.Current;
|
||||
TValue minValue = selector(minItem);
|
||||
results.Add(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey currentItem = enumerator.Current;
|
||||
TValue currentValue = selector(currentItem);
|
||||
int comparisonResult = currentValue.CompareTo(minValue);
|
||||
if (comparisonResult < 0) {
|
||||
minValue = currentValue;
|
||||
results.Clear();
|
||||
results.Add(currentItem);
|
||||
} else if (comparisonResult == 0) {
|
||||
results.Add(currentItem);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 选择最大值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TKey? MaxBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return default;
|
||||
TKey maxItem = enumerator.Current;
|
||||
TValue maxValue = selector(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TValue value = selector(enumerator.Current);
|
||||
if (value.CompareTo(maxValue) <= 0) continue;
|
||||
maxItem = enumerator.Current;
|
||||
maxValue = value;
|
||||
}
|
||||
return maxItem;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择最小值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TKey? MinBy<TKey, TValue>(this IEnumerable<TKey> List, Func<TKey, TValue> Selector) where TValue : IComparable<TValue> {
|
||||
using var enumerator = List.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) { return default; }
|
||||
TKey minItem = enumerator.Current;
|
||||
TValue minValue = Selector(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TValue value = Selector(enumerator.Current);
|
||||
if (value.CompareTo(minValue) >= 0) { continue; }
|
||||
minItem = enumerator.Current;
|
||||
minValue = value;
|
||||
}
|
||||
return minItem;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Join
|
||||
|
||||
/// <summary>
|
||||
/// 用指定的分割符将集合连接为字符串。
|
||||
/// </summary>
|
||||
public static string Join(this IEnumerable list, char split) {
|
||||
var builder = new StringBuilder();
|
||||
bool isFirst = true;
|
||||
foreach (var element in list) {
|
||||
if (isFirst)
|
||||
isFirst = false;
|
||||
else
|
||||
builder.Append(split);
|
||||
if (element is not null) builder.Append(element.ToString());
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 用指定的分割符将集合连接为字符串。
|
||||
/// </summary>
|
||||
public static string Join(this IEnumerable list, string split) {
|
||||
if (split.IsSingle()) return list.Join(split[0]);
|
||||
var builder = new StringBuilder();
|
||||
bool isFirst = true;
|
||||
foreach (var element in list) {
|
||||
if (isFirst)
|
||||
isFirst = false;
|
||||
else
|
||||
builder.Append(split);
|
||||
if (element is not null) builder.Append(element.ToString());
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dictionary
|
||||
|
||||
/// <summary>
|
||||
/// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
|
||||
/// 返回是否确实移除了元素。
|
||||
/// </summary>
|
||||
public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 将二维数组转换为字典。
|
||||
/// </summary>
|
||||
public static Dictionary<T, T> ToDictionary<T>(this T[,] arr) where T : notnull {
|
||||
Dictionary<T, T> result = [];
|
||||
if (arr.Length == 0) return result;
|
||||
if (arr.GetLength(1) != 2) throw new ArgumentException("数组必须为两列,第一列为 Key,第二列为 Value。");
|
||||
for (int i = 0; i < arr.GetLength(0); i++) result[arr[i, 0]] = arr[i, 1];
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
|
||||
/// </summary>
|
||||
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default!) =>
|
||||
dict.TryGetValue(key, out var result) ? result : defaultValue;
|
||||
|
||||
/// <summary>
|
||||
/// 将值添加到字典的对应项的列表中。
|
||||
/// </summary>
|
||||
public static void AddIntoValueCollection<TKey, TValue>(this IDictionary<TKey, List<TValue>> dict, TKey key, TValue value) {
|
||||
if (dict.TryGetValue(key, out var collection)) {
|
||||
collection.Add(value);
|
||||
} else {
|
||||
dict.Add(key, [value]);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 将 <see cref="FlagsAttribute"/> 枚举值解包为它包含的单一 Flag 成员的集合。
|
||||
/// 建议仅对没有极端值的正数枚举使用。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
|
||||
/// </remarks>
|
||||
public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum {
|
||||
foreach (var element in Enum.GetValues(typeof(T)).Cast<T>().Distinct()) {
|
||||
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
|
||||
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值
|
||||
if (value.HasFlag(element)) yield return element;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断集合是否有且仅有一个元素。
|
||||
/// 在输入 null 时返回 false。
|
||||
/// </summary>
|
||||
public static bool IsSingle<T>([AllowNull] this IEnumerable<T> source) {
|
||||
if (source is null) return false;
|
||||
if (source is IList<T> list) return list.Count == 1;
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return false;
|
||||
if (enumerator.MoveNext()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对集合的每个元素执行指定操作。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> ForAll<T>(this IEnumerable<T> source, Action<T> action) {
|
||||
foreach (T item in source) action(item);
|
||||
return source;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class StringExtensions {
|
||||
|
||||
#region 区域性 / 大小写 简化
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 StartsWith。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
/// <summary>
|
||||
/// 高速的 EndsWith。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 忽略大小写的 Contains。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool ContainsIgnoreCase(this string value, string subString) {
|
||||
return value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 IndexOf。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int IndexOfF(this string value, string subString, bool ignoreCase = false) {
|
||||
return value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
/// <summary>
|
||||
/// 高速的 IndexOf。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
|
||||
return value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 LastIndexOf。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false) {
|
||||
return value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
/// <summary>
|
||||
/// 高速的 LastIndexOf。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
|
||||
return value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ToLowerInvariant 的简略写法。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string Lower(this string str) => str.ToLowerInvariant();
|
||||
/// <summary>
|
||||
/// ToUpperInvariant 的简略写法。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string Upper(this string str) => str.ToUpperInvariant();
|
||||
|
||||
#endregion
|
||||
|
||||
#region 分割与裁切
|
||||
|
||||
/// <summary>
|
||||
/// 分割字符串。
|
||||
/// 若原始字符串为空,则返回 {""}。
|
||||
/// </summary>
|
||||
public static string[] Split(this string fullStr, string splitStr) {
|
||||
if (splitStr.IsSingle())
|
||||
return fullStr.Split(splitStr[0]);
|
||||
else
|
||||
return fullStr.Split([splitStr], StringSplitOptions.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// </summary>
|
||||
public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(0, pos);
|
||||
else
|
||||
return str;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// </summary>
|
||||
public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(0, pos);
|
||||
else
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// </summary>
|
||||
public static string AfterFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(pos + text!.Length);
|
||||
else
|
||||
return str;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// </summary>
|
||||
public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(pos + text!.Length);
|
||||
else
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
|
||||
/// 等效于 AfterLast 后接 BeforeFirst。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// </summary>
|
||||
public static string Between(this string str, string after, string before, bool ignoreCase = false) {
|
||||
int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
|
||||
if (startPos >= 0)
|
||||
startPos += after.Length;
|
||||
else
|
||||
startPos = 0;
|
||||
|
||||
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
|
||||
if (endPos >= 0)
|
||||
return str.Substring(startPos, endPos - startPos);
|
||||
else if (startPos > 0)
|
||||
return str.Substring(startPos);
|
||||
else
|
||||
return str;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 替换
|
||||
|
||||
/// <summary>
|
||||
/// 替换字符串中的内容。
|
||||
/// 仅当需要替换时,才调用 <paramref name="newValue"/> 获取结果字符串。
|
||||
/// </summary>
|
||||
public static string ReplaceOnDemand(this string str, string oldValue, Func<string> newValue) =>
|
||||
str.Contains(oldValue) ? str.Replace(oldValue, newValue()) : str;
|
||||
|
||||
/// <summary>
|
||||
/// 将字符串中的换行符统一替换为指定字符。
|
||||
/// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
|
||||
/// </summary>
|
||||
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) =>
|
||||
Regex.Replace(input,
|
||||
mergeMultiple ? @"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+" : @"\r\n|[\n\r\f\u0085\u2028\u2029]",
|
||||
newValue.Replace("$", "$$"), // 避免识别成捕获组
|
||||
RegexOptions.Compiled);
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 将第一个字符转换为大写,其余字符转换为小写。
|
||||
/// </summary>
|
||||
public static string Capitalize(this string word) {
|
||||
if (string.IsNullOrEmpty(word)) return word;
|
||||
return $"{word.Substring(0, 1).Upper()}{word.Substring(1).Lower()}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将字符串统一至某个长度。
|
||||
/// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
|
||||
/// </summary>
|
||||
public static string EnsureLength(this string? str, char code, int length) {
|
||||
if (str == null) str = "";
|
||||
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该字符串中的字符是否均为 ASCII 字符。
|
||||
/// </summary>
|
||||
public static bool IsAsciiOnly(this string input) => input.All(c => c < 128);
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user