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);
}
}
}