首页 > 编程语言 >一个全面且高效的C#帮助类库

一个全面且高效的C#帮助类库

时间:2024-09-14 18:22:26浏览次数:3  
标签:类库 高效 C# System newType item new DataTable row

项目介绍

Common.Utility是一个C#编写的实用工具库,它收集并整理了大量的辅助类,旨在提供一系列方便开发者在.NET环境中使用的功能。


日常工作收集,各式各样的几乎都能找到,所有功能性代码都是独立的类,类与类之间没有联系,可以单独引用至项目。

功能介绍

一个全面且高效的C#帮助类库_C#

一个全面且高效的C#帮助类库_.net_02

CSVHelper

using Quartz.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;

namespace DotNet.Utilities.CSVHelper
{
    public class CSVHelper
    {
       
        /// <summary>
        /// CSV转换成DataTable(OleDb数据库访问方式)
        /// </summary>
        /// <param name="csvPath">csv文件路径</param>
        /// <returns></returns>
        public static DataTable CSVToDataTableByOledb(string csvPath)
        {
            DataTable csvdt = new DataTable("csv");
            if (!File.Exists(csvPath))
            {
                throw new FileNotFoundException("csv文件路径不存在!");
            }

            FileInfo fileInfo = new FileInfo(csvPath);
            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileInfo.DirectoryName + ";Extended Properties='Text;'"))
            {
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + fileInfo.Name + "]", conn);
                adapter.Fill(csvdt);
            }
            return csvdt;
        }

        /// <summary>
        /// CSV转换成DataTable(文件流方式)
        /// </summary>
        /// <param name="csvPath">csv文件路径</param>
        /// <returns></returns>
        public static DataTable CSVToDataTableByStreamReader(string csvPath)
        {
            DataTable csvdt = new DataTable("csv");

            int intColCount = 0;
            bool blnFlag = true;
            DataColumn column;
            DataRow row;
            string strline = null;
            string[] aryline;
            Encoding encoding=null;

            using (StreamReader reader = new StreamReader(csvPath, encoding))
            {
                while (!string.IsNullOrEmpty((strline = reader.ReadLine())))
                {
                    aryline = strline.Split(new char[] { ',' });

                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            column = new DataColumn(aryline[i]);
                            csvdt.Columns.Add(column);
                        }
                        continue;
                    }

                    row = csvdt.NewRow();
                    for (int i = 0; i < intColCount; i++)
                    {
                        row[i] = aryline[i];
                    }
                    csvdt.Rows.Add(row);
                }
            }

            return csvdt;
        }

        /// <summary>
        /// DataTable 生成 CSV
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="csvPath">csv文件路径</param>
        public static void DataTableToCSV(DataTable dt, string csvPath)
        {
            if (null == dt)
                return;

            StringBuilder csvText = new StringBuilder();
            StringBuilder csvrowText = new StringBuilder();
            foreach (DataColumn dc in dt.Columns)
            {
                csvrowText.Append(",");
                csvrowText.Append(dc.ColumnName);
            }
            csvText.AppendLine(csvrowText.ToString().Substring(1));

            foreach (DataRow dr in dt.Rows)
            {
                csvrowText = new StringBuilder();
                foreach (DataColumn dc in dt.Columns)
                {
                    csvrowText.Append(",");
                    csvrowText.Append(dr[dc.ColumnName].ToString().Replace(',', ' '));
                }
                csvText.AppendLine(csvrowText.ToString().Substring(1));
            }

            File.WriteAllText(csvPath, csvText.ToString(), Encoding.Default);
        }
    }
}

DataTable转实体

public static class DataTableExtensions
    {
        public static T ToEntity<T>(this DataTable table) where T : new()
        {
            T entity = new T();
            foreach (DataRow row in table.Rows)
            {
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (row.Table.Columns.Contains(item.Name))
                    {
                        if (DBNull.Value != row[item.Name])
                        {
                            Type newType = item.PropertyType;
                            //判断type类型是否为泛型,因为nullable是泛型类,
                            if (newType.IsGenericType
                                    && newType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
                            {
                                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(newType);
                                //将type转换为nullable对的基础基元类型
                                newType = nullableConverter.UnderlyingType;
                            }

                            item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);

                        }

                    }
                }
            }

            return entity;
        }

        public static List<T> ToEntities<T>(this DataTable table) where T : new()
        {
            List<T> entities = new List<T>();
            if (table == null)
                return null;
            foreach (DataRow row in table.Rows)
            {
                T entity = new T();
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (table.Columns.Contains(item.Name))
                    {
                        if (DBNull.Value != row[item.Name])
                        {
                            Type newType = item.PropertyType;
                            //判断type类型是否为泛型,因为nullable是泛型类,
                            if (newType.IsGenericType
                                    && newType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
                            {
                                //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(newType);
                                //将type转换为nullable对的基础基元类型
                                newType = nullableConverter.UnderlyingType;
                            }
                            item.SetValue(entity, Convert.ChangeType(row[item.Name], newType), null);
                        }
                    }
                }
                entities.Add(entity);
            }
            return entities;
        }
    }

开源地址

https://github.com/laochiangx/Common.Utility

标签:类库,高效,C#,System,newType,item,new,DataTable,row
From: https://blog.51cto.com/u_9849794/12018230

相关文章

  • Spring扩展点系列-BeanFactoryAware
    文章目录简介源码分析示例代码示例一:验证BeanFactoryAware执行顺序示例二:动态获取其他bean示例三:动态bean的状态简介spring容器中Bean的生命周期内所有可扩展的点的调用顺序扩展接口实现接口ApplicationContextlnitializerinitializeAbstractApplicationCo......
  • C++ 顶层const底层const
    inti=0;int*constpl=&i;//不能改变p1的值,这是一个顶层constconstintci=42;//不能改变ci的值,这是一个顶层constconstint*p2=&ci;//允许改变p2的值,这是一个底层constconstint*constp3=p2;//靠右的const是顶层const,靠左的是底层constconstin......
  • capital许可监控工具
    在软件资产日益增长的今天,如何有效管理和监控软件许可,确保合规使用并优化资源,已成为企业面临的重要挑战。Capital许可监控工具,作为一款专业的软件许可监控解决方案,正是为解决这一难题而生。一、Capital许可监控工具的核心价值Capital许可监控工具通过实时追踪和监控软件许可的使......
  • TCP三次握手及四次挥手理解
    定义传输控制协议(TCP,TransmissionControlProtocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议。三次握手三次握手的过程中是没有业务数据传递的,其目的就是确保服务端和客户端能建立连接,方式也很简单,向对方发送的请求有回应就算连接成功,由于没有业务数据的传递,这......
  • c++临时对象导致的生命周期问题
    对象的生命周期是c++中非常重要的概念,它直接决定了你的程序是否正确以及是否存在安全问题。今天要说的临时变量导致的生命周期问题是非常常见的,很多时候没有一定经验甚至没法识别出来。光是我自己写、review、回答别人的问题就犯了或者看到了许许多多这类问题,所以我想有必要......
  • Python的Scapy库详解
    目录前言一、Scapy简介二、基本功能1.构建数据包2.发送与接收数据包3.捕获数据包三、高级功能1.协议栈与数据包叠加2.网络扫描3.数据包注入与攻击模拟四、应用场景五、总结前言Python的Scapy库是一个强大且灵活的网络数据包处理库,常用于网络安全、渗透测......
  • 基于Java实现的漫画之家系统设计与实现(SpringBoot+Vue+MySQL+Tomcat)
    文章目录1.前言2.详细视频演示3.论文参考4.项目运行截图5.技术框架5.1后端采用SpringBoot框架5.2前端框架Vue6.选题推荐毕设案例8.系统测试8.1系统测试的目的8.2系统功能测试9.代码参考10.为什么选择我?11.获取源码1.前言......
  • Codes 开源研发项目管理平台——创新的敏捷测试解决方案
    前言Codes是国内首款重新定义SaaS模式的开源项目管理平台,支持云端认证、本地部署、全部功能开放,并且对30人以下团队免费。它通过整合迭代、看板、度量和自动化等功能,简化测试协同工作,使敏捷测试更易于实施。并提供低成本的敏捷测试解决方案,如同步在线离线测试用例、流程化管......
  • 基于Java实现的家政服务管理平台设计与实现(SpringBoot+Vue+MySQL+Tomcat)
    文章目录1.前言2.详细视频演示3.论文参考4.项目运行截图5.技术框架5.1后端采用SpringBoot框架5.2前端框架Vue6.选题推荐毕设案例8.系统测试8.1系统测试的目的8.2系统功能测试9.代码参考10.为什么选择我?11.获取源码1.前言......
  • LEETCODE 1709 两个日期的最大空档期
      表: UserVisits+-------------+------+|ColumnName|Type|+-------------+------+|user_id|int||visit_date|date|+-------------+------+该表没有主键,它可能有重复的行该表包含用户访问某特定零售商的日期日志。 假设今天的日期是 '2021-1-1......