Skip to content

CodeSnippet-CSharp

约 1806 字大约 6 分钟

CodeSnippetNET

2023-10-11

单例

private static Class _Instance = new Class();
public static Class Instance => _Instance ?? (_Instance = new Class());

截取字符串(C#8+)

string s = "1234567";
string a = s[..1]; //1
string b = s[1..]; //234567
//hashset 无序不重复的列表
int[] ints = new int[15] { 2, 5, 7, 5, 4, 58, 36, 5, 8, 8, 5, 6, 5, 6, 6 };
HashSet<int> set = new HashSet<int>();
foreach (var item in ints)
{
    bool b = set.Add(item);
    Console.WriteLine(b);//元素已存在不会添加进去 false
}

数组转换

int[] rect = rectstr.Split(',').Select(int.Parse).ToArray();

Any()

var imagePaths = files.Where(t => new[] { ".png", ".jpg"}.Any(t.ToLower().EndsWith)).ToArray();

递归

//递归求和
    function getSum(n) {
        if (n === 1) {
            return 1;
        }
        //返回 n 和前 n-1 的和相加
        return n + getSum(n - 1);
    }
//部门树
//List<DepartmentDto> list = Recursive(departmentInfos, 0);
public List<DepartmentDto> Recursive(List<DepartmentDto> list, int parentid)
    {
    List<DepartmentDto> dlist = new List<DepartmentDto>();
    var clist = list.Where(t => t.parentId == parentid).ToList();
    foreach (var item in clist)
    {
        DepartmentDto model = new DepartmentDto
        {
            id = item.id,
            createTime = item.createTime,
            order = item.order,
            parentId = item.parentId,
            department_name = item.department_name,
            children = Recursive(list, item.id),
        };
        dlist.Add(model);
    }
    return dlist;
}

在Windows资源管理器中打开文件并选中


if (!System.IO.File.Exists(filePath)) return;

Process.Start("explorer.exe", $"/select,{filePath}");

递归文件夹 统计文件数量

//获取所有文件与文件夹
public static List<FileData> GetDirectory(string directoryPath)
{
    List<FileData> list = new List<FileData>();
    if (Directory.Exists(directoryPath))
    {
        DirectoryInfo dir = new DirectoryInfo(directoryPath);
        var dirinfo = new FileData
        {
            FileName = dir.Name,
            FileNameFull = dir.FullName,
            child = new List<FileData>(),
        };
        //Directory.GetFiles(_inputImgFolder, "*.jpg", SearchOption.TopDirectoryOnly);
        foreach (string file in Directory.GetFiles(directoryPath))
        {
            FileInfo fileInfo = new FileInfo(file);
            var child = new FileData
            {
                FileName = fileInfo.Name,
                FileNameFull = fileInfo.FullName,
                ExtionName = fileInfo.Name,
            };
            dirinfo.child.Add(child);
        }
        foreach (string subDirectory in Directory.GetDirectories(directoryPath))
        {
            dirinfo.child.AddRange(GetDirectory(subDirectory));
        }
        list.Add(dirinfo);
    }
    return list;
}

public enum TJTYPE
{ all = 0,dir = 1,file = 2,}
//统计所有文件的数量
public static int CountData(FileData fileData, TJTYPE type)
{
    int count =1;
	if (type == TJTYPE.dir && !string.IsNullOrEmpty(fileData.ExtionName))
	    count = 0; // 文件夹数量
	else if (type == TJTYPE.file && string.IsNullOrEmpty(fileData.ExtionName))
	    count = 0; // 文件数量
	    
    if (fileData.child != null)
        fileData.child.ForEach(f => { count += CountData(f, type); });
    return count;
}
/// <summary>
/// 递归备份
/// </summary>
/// <param name="source_path">备份文件路径</param>
/// <param name="target_path">备份到..</param>
/// <returns></returns>
public bool CopyIoFile(string source_path, string target_path)
{
    _logger.Info("====执行文件备份=====");
    if (textBox5.Text.ToLower().Split('|').Contains(Path.GetFileName(source_path).ToLower()))
        return false;
    if (!Directory.Exists(target_path))
        Directory.CreateDirectory(target_path);
    string[] files = Directory.GetFiles(source_path);
    foreach (string file in files)
    {
        File.Copy(file, Path.Combine(target_path, Path.GetFileName(file)), true);
    }
    var folders = Directory.GetDirectories(source_path);
    foreach (string folder in folders)
    {
        CopyIoFile(folder, Path.Combine(target_path, Path.GetFileName(folder)));
    }
    logger.Info("====执行文件备份结束=====");
    return true;
}

图片去黑边

public static void RemoveBlackBorder(string imagePath)
{
    // 加载图像
    Bitmap image = new Bitmap(imagePath);
    Color blackColor = Color.FromArgb(0, 0, 0); // 黑色
    // 检测上边界
    top = 0;
    for (int y = 0; y < image.Height; y++)
    {
	    for (int x = 0; x < image.Width; x++)
        {
            if (image.GetPixel(x, y) != blackColor)
            {
                top = y;
                    break;
            }
        }
        if (top != 0)
            break;
    }
            // 检测下边界
    int bottom = image.Height - 1;
    for (int y = image.Height - 1; y >= 0; y--)
    {
        for (int x = 0; x < image.Width; x++)
        {
            if (image.GetPixel(x, y) != blackColor)
            {
                bottom = y;
                break;
                }
            }
            if (bottom != image.Height - 1)
                break;
    }
    // 检测左边界
    int left = 0;
    for (int x = 0; x < image.Width; x++)
    {
	    for (int y = 0; y < image.Height; y++)
	    {
            if (image.GetPixel(x, y) != blackColor)
            {
                left = x;
                break;
            }
        }
        if (left != 0)
            break;
    }

            // 检测右边界
    int right = image.Width - 1;
    for (int x = image.Width - 1; x >= 0; x--)
    {
        for (int y = 0; y < image.Height; y++)
        {
            if (image.GetPixel(x, y) != blackColor)
            {
                right = x;
                break;
            }
        }
        if (right != image.Width - 1)
            break;
    }

    // 裁剪图像
    int newWidth = right - left + 1;
    int newHeight = bottom - top + 1;

    Rectangle cropRect = new Rectangle(left, top, newWidth, newHeight);
    Bitmap croppedImage = image.Clone(cropRect, image.PixelFormat);

    // 保存图像
    croppedImage.Save("cropped_image.jpg");
}

身份证算年龄

//身份证算年龄 
public static int CalculateAge(string identityCard)
{
    string Birthday = "";
    if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
        Birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);

    if (identityCard.Length == 15)
        Birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);

    DateTime birthDate = DateTime.Parse(Birthday);
    DateTime nowDateTime = DateTime.Now;
    int age = nowDateTime.Year - birthDate.Year;
    if (nowDateTime.Month < birthDate.Month || (nowDateTime.Month == birthDate.Month && nowDateTime.Day < birthDate.Day))
    {
        age--;
    }
    return age;
}

GroupBy单字段 多字段分组

  txt_sample_list.GroupBy(g => g.ItemsCode).Select(s => new { name = s.Key, total = s.Count(),alltotal = s.sum(ss=>ss.sumer) }); //审核的细胞分类及总数

  txt_sample_list.GroupBy(g => new { g.ItemCode, g.ItemsCode }).Select(s => new Result { Name = s.Key.checkItemCode, GroupName = s.Key.checkItemsCode, detectionProjectCellSum = s.Count() })

操作ZIP

//创建zip往里边添加文件夹
using (ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
    // 遍历文件夹中的所有文件和子文件夹
    string[] allFiles = Directory.GetFiles(sourceFolderPath, "*", SearchOption.AllDirectories);

    foreach (string filePath in allFiles)
    {
        // 获取文件在ZIP中的相对路径
        string entryPath = filePath.Replace(sourceFolderPath, "").TrimStart('\\');
        // 创建ZIP条目并将文件添加到ZIP文件
        zipArchive.CreateEntryFromFile(filePath, entryPath);
    }
}


// 解压缩ZIP文件到指定目录
ZipFile.ExtractToDirectory(zipPath, extractPath);


// 打开ZIP文件并遍历条目
foreach (ZipArchiveEntry entry in zipArchive.Entries)
{
    //如果是sql文件直接用流取出来
    if (entry.Name.Contains("samplesql_" + item.Sample_Number.TrimEnd(".zip".ToArray())))
    {
        using (StreamReader reader = new StreamReader(entry.Open(), Encoding.UTF8))
        {
            string sql = reader.ReadToEnd();
            bool r = Sqlitehp.ExecuteCommand(sql);
            if (r) Frm_Form1.Frm_Form.SettipMsg($"恢复到数据库成功!", 1000);
        }
    }
    else
    {
        string extract_dirpath = Path.Combine(restore_path,Path.GetDirectoryName(entry.FullName)); 
        if (!Directory.Exists(extract_dirpath)) 
        { 
	        Directory.CreateDirectory(extract_dirpath); 
        }
        string extract_path = Path.Combine(restore_path, entry.FullName);
        entry.ExtractToFile(extract_path, true);
    }
}

随机中文

public static string randomstr(int len)
{
    string str = "";
    Random random = new Random();
    for (int i = 0; i < len; i++)
    {
        int asciiCode = random.Next(0x4e00, 0x9fa5 + 1); //中文字符的 ASCII 码范围是 0x4e00 ~ 0x9fa5
        str += (char)asciiCode;
    }
    return str;
}

反射

var all = list.Select(item => item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(d => d.Name, pp => pp.GetValue(item)).ToList());

//全部或则单独
for (int i = 0; i < list.Count; i++)
{
    var bcd = (from t in propertys where t.GetValue(list[i]) != null select new KeyValuePair<string, object>($"`{t.Name}{i}`", t.GetValue(list[i]))).ToDictionary(d => d.Key, pp => pp.Value).ToList();

    paras.Add("(" + string.Join(",", propertys.Select(s => $"`@{s.Name}{i}`")) + ")");
}

反射判断类型是否可为空

 Type propertyType = type.PropertyType;
 bool IsNullable = propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>);

驼峰转下划线

public static List<string> ConvertHumps(List<string> strarr)
{
    string pattern = @"(?<!^)([A-Z])";
    string replacement = "_$1";
    List<string> xiahuaxian = new List<string>();
    for (int i = 0; i < strarr.Count; i++)
    {
        string underscoreCase = Regex.Replace(strarr[i], pattern, replacement);
        xiahuaxian.Add(underscoreCase.ToLower());
    }
        return xiahuaxian;
}

枚举转键值对

///枚举转键值对,枚举的描述为key,int值为value
Type enumType = typeof(DiagnosisState);
var b = Enum.GetValues(enumType).Cast<DiagnosisState>()
    .ToDictionary(k =>
                 {
                     FieldInfo field = enumType.GetField(k.ToString());
                     DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>();
                     return attribute != null ? attribute.Description : k.ToString();
                 },
                 v => (int)v);

Process.Start启动外部程序目录的问题

Process.Start("path");
// 普通的Process.Start方法会继承当前进程的基础目录。 
// 可以使用ProcessStartInfo显式设置打开程序的基础目录来避免这个问题
//     ↓           ↓             ↓             ↓
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "MarrowAnalysis.exe"; // 启动的程序的文件名
psi.WorkingDirectory = AppConfigHelper.GetValue("ProcessAddress"); // 设置基础目录
Process.Start(psi);

AOP代理 - Castle.DynamicProxy

   protected override IContainerExtension CreateContainerExtension()
        {
            IContainerExtension containerExtension = base.CreateContainerExtension();
            containerExtension.ConfigureContainer(_Configuration);

            containerExtension.Register<ITest2Service, Test2Service>();
            var LogHandlerInterface = Core.App.EffectiveTypes.Where(t => t.IsDefined(typeof(LogHandlerAttribute), false) && t.IsInterface); //获取所有接口
            foreach (var interfacetype in LogHandlerInterface)
            {
                var proxyGenerator = new ProxyGenerator();
                var interceptor = new MyInterceptor(containerExtension.Resolve<Serilog.ILogger>());
                var target = containerExtension.Resolve(interfacetype);//获取容器中接口的实现
                var aad = proxyGenerator.CreateInterfaceProxyWithTarget(interfacetype, target, interceptor); //前面接口,后面是实现;结合起来即可实现aop拦截
                containerExtension.RegisterInstance(interfacetype, aad);
            }
            return containerExtension;
        }



 protected override IContainerExtension CreateContainerExtension()
        {
            IContainerExtension containerExtension = base.CreateContainerExtension();


            containerExtension.ConfigureContainer(_Configuration);

            //containerExtension.Register<ITest2Service, Test2Service>();
            //var LogHandlerInterface = Core.App.EffectiveTypes.Where(t => t.IsDefined(typeof(LogHandlerAttribute), false) && t.IsInterface);
            IUnityContainer unityContainer = ((IContainerProvider)containerExtension).GetContainer();
            var LogHandlerInterface = unityContainer.Registrations.Where(t => t.RegisteredType.IsDefined(typeof(LogHandlerAttribute), false));
            foreach (var item in LogHandlerInterface)
            {
                var proxyGenerator = new ProxyGenerator();
                var interceptor = new MyInterceptor(containerExtension.Resolve<Serilog.ILogger>());
                var aaaa = containerExtension.Resolve(item);
                var aad = proxyGenerator.CreateInterfaceProxyWithTarget(item, aaaa, interceptor); //前面接口,后面是实现  
                containerExtension.RegisterInstance(item,aad);
            }
            //var proxyGenerator = new ProxyGenerator();
            //var interceptor = new MyInterceptor(Log.Logger);
            //containerExtension.RegisterInstance(
            //    proxyGenerator.CreateInterfaceProxyWithTarget<ITest2Service>(containerExtension.Resolve<ITest2Service>(), interceptor));

            return containerExtension;
        }


//自身容器完成
public static void FeatureInjectionAOP(this IContainerExtension containerExtension)
{
        var proxyGenerator = new ProxyGenerator();
        var interceptor = new MyInterceptor(containerExtension.Resolve<Serilog.ILogger>());
        IUnityContainer unityContainer = ((IContainerProvider)containerExtension).GetContainer();
        var LogHandlerInterface = unityContainer.Registrations.Where(t => t.RegisteredType.IsDefined(typeof(LogHandlerAttribute), false));
        foreach (var interfacetype in LogHandlerInterface)
        {
            var target = containerExtension.Resolve(interfacetype.RegisteredType);
            var a = proxyGenerator.CreateInterfaceProxyWithTarget(interfacetype.RegisteredType, target, interceptor);
            containerExtension.RegisterInstance(interfacetype.RegisteredType, a);
        }
}

委托属性传值

 public class SimpleAction
 {
     public Action<int> Progress { get; set; }
     public void ExecAction()
     {
         for (int i = 0; i < 10; i++)
         {
             Thread.Sleep(500);
             Progress.Invoke(i);
         }
     }
 }


public partial class MainWindow : Window
{
    public MainWindow()
    {
         InitializeComponent();
    }
	private void async_Click(object sender, RoutedEventArgs e)
	{
	    Debug.WriteLine("1111111");
	    SimpleAction simple = new SimpleAction();
	
	    simple.Progress = p =>
	    {
		    //需要注意如果该委托内部有执行耗时的用异步,不然会累加时长,很慢: Task.Run();
	        Debug.WriteLine("进度:" + p);
	    };
	
	    simple.ExecAction();
	    Debug.WriteLine("2222222");
	}
}

/*输出:
	1111111
	进度:0
	进度:1
	进度:2
	进度:3
	进度:4
	进度:5
	进度:6
	进度:7
	进度:8
	2222222
	进度:9
*/

计时器

public static T Time<T>(string label, Func<T> func)
{
    var sw = Stopwatch.StartNew();
    try
    {
        return func();
    }
    finally
    {
        Console.WriteLine($"{label}: {sw.Elapsed.TotalMilliseconds:F2} ms");
    }
}

// 使用:
void Function()
{
    Time("循环", () =>
    {
        for (int i = 0; i < 100; i++)
            Console.Write("Hello \n");
        return 0; // 可返回任意值
    });
}