1.String
public static class StringExtensions
{/// <summary>/// 字符串轉List(中逗 英逗分隔)/// </summary>public static List<string> SplitCommaToList(this string data){if (string.IsNullOrEmpty(data)){return new List<string>();}data = data.Replace(",", ",");//中文逗號轉化為英文return data.Split(",").ToList();}/// <summary>/// 字典按序替換字符串(用key代替value)/// </summary>/// <returns></returns>public static string DictionaryReplace(this string input, Dictionary<string, string> replacements){if (string.IsNullOrEmpty(input) || replacements == null || replacements.Count == 0){return input;}foreach (var replacement in replacements){input = input.Replace(replacement.Value, replacement.Key);//用key代替value}return input;}/// <summary>/// 反序列化成實體/// </summary>public static T ConvertToEntity<T>(this string json)//可傳入列表,實體{return JsonSerializer.Deserialize<T>(json);}}
2.DateTime
3.List
public static class ListExtensions
{/// <summary>/// 例如輸入1 3 輸出第1個(含)到第3個(含)的實體列表/// </summary>public static List<T> GetRangeList<T>(this List<T> list, int startIndex, int endIndex){// 檢查索引范圍是否有效if (startIndex < 1 || endIndex > list.Count || startIndex > endIndex){//throw new ArgumentOutOfRangeException("輸入的索引值超出了列表的長度或范圍不正確!");return new List<T>();}// 返回指定范圍內的元素return list.GetRange(startIndex - 1, endIndex - startIndex + 1);}/// <summary>/// 傳入列表和需要獲取的數量,返回隨機選出的元素/// </summary>/// <returns></returns>public static List<T> GetRandomList<T>(this List<T> list, int count){// 檢查列表是否足夠if (list.Count < count){//throw new ArgumentException("列表中的元素不足,無法隨機選擇所需數量的元素。");return new List<T>();}// 使用 Random 類生成隨機索引Random random = new Random();// 隨機選擇不重復的元素return list.OrderBy(x => random.Next()).Take(count).ToList();}/// <summary>/// 按指定字段,順序排序,且返回xx條/// </summary>/// <returns></returns>public static List<V> OrderByAndTake<T, V>(this List<V> list, Expression<Func<V, T>> keySelector, int count){if (list == null || !list.Any() || count <= 0){return new List<V>();}var sortedlist = list.OrderBy(keySelector.Compile());return sortedlist.Take(count).ToList();}/// <summary>/// 按指定字段,倒序排序,且返回xx條/// </summary>/// <returns></returns>public static List<V> OrderByDescAndTake<T, V>(this List<V> list, Expression<Func<V, T>> keySelector, int count){if (list == null || !list.Any() || count <= 0){return new List<V>();}var sortedlist = list.OrderByDescending(keySelector.Compile());return sortedlist.Take(count).ToList();}/// <summary>/// 傳入列表,返回一個元組(索引,列表實體)/// </summary>/// <returns></returns>public static List<(int index , T entity)> GetIndexList<T>(this List<T> list){List<(int index, T entity)> result = new List<(int index, T entity)>();for (int i = 0; i < list.Count; i++){result.Add((i, list[i]));}return result;}/// <summary>/// 列表為null或空列表則返回True/// </summary>/// <returns></returns>public static bool IsNullOrEmpty<T>(this List<T> list){return list == null || !list.Any();}/// <summary>/// 一個實體列表映射到另一個實體列表(屬性名稱相同則映射)/// </summary>public static List<TTarget> MapToList<TTarget>(this IEnumerable<object> sourceList) where TTarget : new(){var targetList = new List<TTarget>();foreach (var source in sourceList){var target = new TTarget();var sourceProperties = source.GetType().GetProperties(); // 使用實際對象的類型var targetProperties = typeof(TTarget).GetProperties();foreach (var sourceProp in sourceProperties){var targetProp = targetProperties.FirstOrDefault(tp => tp.Name == sourceProp.Name && tp.CanWrite);if (targetProp != null && targetProp.PropertyType == sourceProp.PropertyType){targetProp.SetValue(target, sourceProp.GetValue(source));}}targetList.Add(target);}return targetList;}/// <summary>/// 列表轉JSON(string)/// </summary>/// <returns></returns>public static string ConvertToJson<T>(this List<T> sourceList)//可傳入列表,實體{var options = new JsonSerializerOptions{Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁用 Unicode 轉義,防止中文字符轉義為 Unicode};return JsonSerializer.Serialize(sourceList, options);}}
4.Entity
public static class EntityExtensions
{/// <summary>/// 實體轉JSON/// </summary>public static string ConvertToJson<T>(T entity)//可傳入列表,實體{var options = new JsonSerializerOptions{Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁用 Unicode 轉義,防止中文字符轉義為 Unicode};return JsonSerializer.Serialize(entity, options);}/// <summary>/// 將一個實體映射到另一個實體(屬性名稱相同且類型匹配的屬性將映射)/// </summary>public static TTarget MapToEntity<TTarget>(this object source) where TTarget : new(){var target = new TTarget();var sourceProperties = source.GetType().GetProperties(); // 獲取源實體的屬性var targetProperties = typeof(TTarget).GetProperties(); // 獲取目標實體的屬性foreach (var sourceProp in sourceProperties){var targetProp = targetProperties.FirstOrDefault(tp => tp.Name == sourceProp.Name && tp.CanWrite);if (targetProp != null && targetProp.PropertyType == sourceProp.PropertyType){targetProp.SetValue(target, sourceProp.GetValue(source));}}return target;}/// <summary>/// 通過反射設置實體的值/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static void SetValueByReflect<T>(this T entity, string feildName, object feildValue) where T : class{var feild = typeof(T).GetProperty(feildName);var feildType = feild?.PropertyType;if (feild != null && feildType != null){var valueToSet = Convert.ChangeType(feildValue, feildType);//輸入的值類型轉化為實體屬性的類型feild.SetValue(entity, valueToSet);}}
}