C#高级:常用的扩展方法大全

1.String

cs 复制代码
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

cs 复制代码
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

cs 复制代码
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);
        }
    }
}
相关推荐
白宇横流学长1 小时前
基于SpringBoot实现的垃圾分类管理系统
java·spring boot·后端
sali-tec7 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
45288655上山打老虎7 小时前
C++完美转发
java·jvm·c++
Seven977 小时前
查找算法
java
南棱笑笑生8 小时前
20251211给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-6.1】系统时适配OV5645摄像头
windows·rockchip
毕设源码-朱学姐8 小时前
【开题答辩全过程】以 公务员考试在线测试系统为例,包含答辩的问题和答案
java
serendipity_hky8 小时前
【SpringCloud | 第2篇】OpenFeign远程调用
java·后端·spring·spring cloud·openfeign
RwTo8 小时前
【源码】-Java线程池ThreadPool
java·开发语言
SadSunset8 小时前
(15)抽象工厂模式(了解)
java·笔记·后端·spring·抽象工厂模式
兮动人8 小时前
EMT4J定制规则版:Java 8→17迁移兼容性检测与规则优化实战
java·开发语言·emt4j