livia-test/Livia/Utility/UtilityExtensions.cs
2025-03-28 14:31:53 +08:00

65 lines
2.1 KiB
C#

using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Media.Imaging;
namespace Livia.Utility;
public static class UtilityExtensions
{
public static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals
};
public static string RemoveAllWhiteSpace(this string str)
{
return string.Concat(str.Where(c => !char.IsWhiteSpace(c)));
}
public static void AddRange<T>(this ObservableCollection<T> list, IEnumerable<T> items)
{
foreach (T item in items)
{
list.Add(item);
}
}
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
using MemoryStream memoryStream = new();
bitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
public static void AddToCollectionWithKey<TKey, TCollection, TValue>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value) where TCollection : ICollection<TValue>, new() where TKey : notnull
{
if (!dictionary.TryGetValue(key, out TCollection? collection))
{
collection = new TCollection();
dictionary.Add(key, collection);
}
collection.Add(value);
}
public static void AddToCollectionWithKey<TKey, TValue>(this IDictionary<TKey, ConcurrentBag<TValue>> dictionary, TKey key, TValue value) where TKey : notnull
{
if (!dictionary.TryGetValue(key, out ConcurrentBag<TValue>? collection))
{
collection = new ConcurrentBag<TValue>();
dictionary.Add(key, collection);
}
collection.Add(value);
}
}