以下是学习笔记:
参考:https://www.bilibili.com/video/BV1LK4y1k7HM?t=2583 感谢朝夕教育
一,项目框架介绍:
二,数据库的分析和创建
1,数据库的设计:
2,创建数据库的过程:
USE [master] GO /****** Object: Database [RightDBase] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ --数据库文件路径:'D:课程新课程DBase' 改成本地存在的路径 --CREATE DATABASE [RightDBase] CREATE DATABASE RightDBase CONTAINMENT = NONE ON PRIMARY --( NAME = N'RightDBase', FILENAME = N'D:课程新课程DBaseRightDBase.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) ( NAME = 'RightDBase', FILENAME = 'D:DBRightDBase.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON --( NAME = N'RightDBase_log', FILENAME = N'D:课程新课程DBaseRightDBase_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) ( NAME = 'RightDBase_log', FILENAME = 'D:DBRightDBase_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) ALTER DATABASE [RightDBase] SET COMPATIBILITY_LEVEL = 110 GO GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) begin EXEC [RightDBase].[dbo].[sp_fulltext_database] @action = 'enable' end GO ALTER DATABASE [RightDBase] SET ANSI_NULL_DEFAULT OFF GO ALTER DATABASE [RightDBase] SET ANSI_NULLS OFF GO ALTER DATABASE [RightDBase] SET ANSI_PADDING OFF GO ALTER DATABASE [RightDBase] SET ANSI_WARNINGS OFF GO ALTER DATABASE [RightDBase] SET ARITHABORT OFF GO ALTER DATABASE [RightDBase] SET AUTO_CLOSE OFF GO ALTER DATABASE [RightDBase] SET AUTO_CREATE_STATISTICS ON GO ALTER DATABASE [RightDBase] SET AUTO_SHRINK OFF GO ALTER DATABASE [RightDBase] SET AUTO_UPDATE_STATISTICS ON GO ALTER DATABASE [RightDBase] SET CURSOR_CLOSE_ON_COMMIT OFF GO ALTER DATABASE [RightDBase] SET CURSOR_DEFAULT GLOBAL GO ALTER DATABASE [RightDBase] SET CONCAT_NULL_YIELDS_NULL OFF GO ALTER DATABASE [RightDBase] SET NUMERIC_ROUNDABORT OFF GO ALTER DATABASE [RightDBase] SET QUOTED_IDENTIFIER OFF GO ALTER DATABASE [RightDBase] SET RECURSIVE_TRIGGERS OFF GO ALTER DATABASE [RightDBase] SET DISABLE_BROKER GO ALTER DATABASE [RightDBase] SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO ALTER DATABASE [RightDBase] SET DATE_CORRELATION_OPTIMIZATION OFF GO ALTER DATABASE [RightDBase] SET TRUSTWORTHY OFF GO ALTER DATABASE [RightDBase] SET ALLOW_SNAPSHOT_ISOLATION OFF GO ALTER DATABASE [RightDBase] SET PARAMETERIZATION SIMPLE GO ALTER DATABASE [RightDBase] SET READ_COMMITTED_SNAPSHOT OFF GO ALTER DATABASE [RightDBase] SET HONOR_BROKER_PRIORITY OFF GO ALTER DATABASE [RightDBase] SET RECOVERY FULL GO ALTER DATABASE [RightDBase] SET MULTI_USER GO ALTER DATABASE [RightDBase] SET PAGE_VERIFY CHECKSUM GO ALTER DATABASE [RightDBase] SET DB_CHAINING OFF GO ALTER DATABASE [RightDBase] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) GO ALTER DATABASE [RightDBase] SET TARGET_RECOVERY_TIME = 0 SECONDS GO EXEC sys.sp_db_vardecimal_storage_format N'RightDBase', N'ON' GO USE [RightDBase] GO /****** Object: Table [dbo].[MenuInfos] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[MenuInfos]( [MenuId] [int] IDENTITY(1,1) NOT NULL, [MenuName] [nvarchar](50) NOT NULL, [ParentId] [int] NOT NULL, [FrmName] [varchar](500) NULL, [MKey] [nchar](10) NULL, CONSTRAINT [PK_MenuInfos] PRIMARY KEY CLUSTERED ( [MenuId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[RoleInfos] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[RoleInfos]( [RoleId] [int] IDENTITY(1,1) NOT NULL, [RoleName] [nvarchar](50) NULL, [Remark] [nvarchar](500) NULL, [IsAdmin] [int] NOT NULL, CONSTRAINT [PK_RoleInfos] PRIMARY KEY CLUSTERED ( [RoleId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[RoleMenuInfos] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[RoleMenuInfos]( [RMId] [int] IDENTITY(1,1) NOT NULL, [RoleId] [int] NOT NULL, [MenuId] [int] NOT NULL, CONSTRAINT [PK_RoleMenuInfos] PRIMARY KEY CLUSTERED ( [RMId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[UserInfos] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[UserInfos]( [UserId] [int] IDENTITY(101,1) NOT NULL, [UserName] [varchar](20) NOT NULL, [UserPwd] [varchar](50) NOT NULL, CONSTRAINT [PK_UserInfos] PRIMARY KEY CLUSTERED ( [UserId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[UserRoleInfos] Script Date: 2020/4/3 星期五 下午 8:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[UserRoleInfos]( [URId] [int] IDENTITY(1,1) NOT NULL, [UserId] [int] NOT NULL, [RoleId] [int] NOT NULL, CONSTRAINT [PK_UserRoleInfos] PRIMARY KEY CLUSTERED ( [URId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET IDENTITY_INSERT [dbo].[MenuInfos] ON INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (1, N'系统管理', 0, NULL, NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (2, N'新增菜单', 1, N'sm.FrmAddMenuInfo', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (3, N'菜单列表', 1, N'sm.FrmMenuList', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (4, N'角色列表', 1, N'sm.FrmRoleList', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (5, N'权限分配', 1, N'sm.FrmRight', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (6, N'用户列表', 1, N'sm.FrmUserList', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (8, N'新增用户', 6, N'sm.FrmUserInfo', NULL) INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (10, N'成绩管理', 0, N'', N'Alt+S ') INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (11, N'成绩列表', 10, N'score.FrmScoreList', N' ') INSERT [dbo].[MenuInfos] ([MenuId], [MenuName], [ParentId], [FrmName], [MKey]) VALUES (12, N'成绩信息', 10, N'score.FrmScoreInfo', N' ') SET IDENTITY_INSERT [dbo].[MenuInfos] OFF SET IDENTITY_INSERT [dbo].[RoleInfos] ON INSERT [dbo].[RoleInfos] ([RoleId], [RoleName], [Remark], [IsAdmin]) VALUES (1, N'超级管理员', N'具有一切权限', 1) INSERT [dbo].[RoleInfos] ([RoleId], [RoleName], [Remark], [IsAdmin]) VALUES (3, N'系统管理员', N'负责系统管理功能。ssssssssddddd', 0) INSERT [dbo].[RoleInfos] ([RoleId], [RoleName], [Remark], [IsAdmin]) VALUES (4, N'成绩管理员', N'负责成绩信息管理', 0) SET IDENTITY_INSERT [dbo].[RoleInfos] OFF SET IDENTITY_INSERT [dbo].[RoleMenuInfos] ON INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (7, 3, 1) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (8, 3, 2) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (9, 3, 3) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (10, 3, 6) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (11, 3, 8) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (12, 4, 10) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (13, 4, 11) INSERT [dbo].[RoleMenuInfos] ([RMId], [RoleId], [MenuId]) VALUES (14, 4, 12) SET IDENTITY_INSERT [dbo].[RoleMenuInfos] OFF SET IDENTITY_INSERT [dbo].[UserInfos] ON INSERT [dbo].[UserInfos] ([UserId], [UserName], [UserPwd]) VALUES (101, N'admin', N'admin') INSERT [dbo].[UserInfos] ([UserId], [UserName], [UserPwd]) VALUES (102, N'lyc001', N'123456') SET IDENTITY_INSERT [dbo].[UserInfos] OFF SET IDENTITY_INSERT [dbo].[UserRoleInfos] ON INSERT [dbo].[UserRoleInfos] ([URId], [UserId], [RoleId]) VALUES (1, 101, 1) INSERT [dbo].[UserRoleInfos] ([URId], [UserId], [RoleId]) VALUES (3, 102, 3) SET IDENTITY_INSERT [dbo].[UserRoleInfos] OFF ALTER TABLE [dbo].[RoleInfos] ADD CONSTRAINT [DF_RoleInfos_IsAdmin] DEFAULT ((0)) FOR [IsAdmin] GO ALTER TABLE [dbo].[RoleMenuInfos] WITH CHECK ADD CONSTRAINT [FK_RoleMenuInfos_RoleInfos] FOREIGN KEY([RoleId]) REFERENCES [dbo].[RoleInfos] ([RoleId]) GO ALTER TABLE [dbo].[RoleMenuInfos] CHECK CONSTRAINT [FK_RoleMenuInfos_RoleInfos] GO ALTER TABLE [dbo].[UserRoleInfos] WITH CHECK ADD CONSTRAINT [FK_UserRoleInfos_RoleInfos] FOREIGN KEY([UserId]) REFERENCES [dbo].[UserInfos] ([UserId]) GO ALTER TABLE [dbo].[UserRoleInfos] CHECK CONSTRAINT [FK_UserRoleInfos_RoleInfos] GO ALTER TABLE [dbo].[UserRoleInfos] WITH CHECK ADD CONSTRAINT [FK_UserRoleInfos_RoleInfos1] FOREIGN KEY([RoleId]) REFERENCES [dbo].[RoleInfos] ([RoleId]) GO ALTER TABLE [dbo].[UserRoleInfos] CHECK CONSTRAINT [FK_UserRoleInfos_RoleInfos1] GO USE [master] GO ALTER DATABASE [RightDBase] SET READ_WRITE GO
三,数据访问
1,通用数据访问类
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PM.DAL.Helper { /// <summary> /// 数据库帮助类(工具类) 静态类操作起来更快 /// </summary> public static class DBHelper { /// <summary> /// 连接字符串 /// </summary> private static string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; /// <summary> /// 增、删、改的通用方法 /// 执行Sql语句或存储过程,返回受影响的行数 /// SQL注入 /// </summary> /// <param name="sql">sql语句或存储过程名</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static int ExecuteNonQuery(string sql,int cmdType,params SqlParameter[] parameters) { //select @@Identity 返回上一次插入记录时自动产生的ID int result = 0;//返回结果 using (SqlConnection conn = new SqlConnection(connStr)) { //执行脚本的对象cmd SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); result = cmd.ExecuteNonQuery();//执行T-SQL并返回受影响行数 cmd.Parameters.Clear(); } //using原理:类似于try finally return result; } /// <summary> /// 执行sql查询,返回第一行第一列的值 /// </summary> /// <param name="sql">sql语句或存储过程</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static object ExecuteScalar(string sql,int cmdType, params SqlParameter[] parameters) { //params 只能写在一维数组之前,且只能标识参数列表中的最后一个参数 //select @@Identity 返回上一次插入记录时自动产生的ID object result = null;//返回结果 using (SqlConnection conn = new SqlConnection(connStr)) { //执行脚本的对象cmd SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); result = cmd.ExecuteScalar();//执行T-SQL并返回第一行第一列的值 cmd.Parameters.Clear(); if (result == null || result == DBNull.Value) { return null; } else { return result; } } } /// <summary> /// 执行sql查询,返回SqlDataReader对象 /// </summary> /// <param name="sql">sql语句或存储过程</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static SqlDataReader ExecuteReader(string sql,int cmdType,params SqlParameter[] parameters) { SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); SqlDataReader reader; try { reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return reader; } catch (Exception ex) { conn.Close(); throw new Exception("创建reader对象发生异常", ex); } } /// <summary> /// 执行查询,查询结果填充到DataTable 只针对查询一个表的情况 /// </summary> /// <param name="sql">sql语句或存储过程</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static DataTable GetDataTable(string sql,int cmdType,params SqlParameter[] parameters) { DataTable dt = null; using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); SqlDataAdapter da = new SqlDataAdapter(cmd); dt = new DataTable(); da.Fill(dt); } return dt; } /// <summary> /// 执行查询,数据填充到DataSet /// </summary> /// <param name="sql">sql语句或存储过程</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static DataSet GetDataSet(string sql, int cmdType, params SqlParameter[] parameters) { DataSet ds = null; using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); //数据适配器 //conn 自动打开 断开式连接 SqlDataAdapter da = new SqlDataAdapter(cmd); ds = new DataSet(); da.Fill(ds); //自动关闭conn } return ds; } /// <summary> /// 事务 执行批量sql /// </summary> /// <param name="listSql"></param> /// <returns></returns> public static bool ExecuteTrans(List<string> listSql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlTransaction trans = conn.BeginTransaction(); SqlCommand cmd = BuilderCommand(conn, "", 1, trans); try { int count = 0; for (int i = 0; i < listSql.Count; i++) { if (listSql[i].Length > 0) { cmd.CommandText = listSql[i]; cmd.CommandType = CommandType.Text; count += cmd.ExecuteNonQuery(); } } trans.Commit(); return true; } catch (Exception ex) { trans.Rollback(); throw new Exception("执行事务出现异常", ex); } } } /// <summary> /// 事务 批量执行 CommandInfo 包括sql,脚本类型,参数列表 /// </summary> /// <param name="comList"></param> /// <returns></returns> public static bool ExecuteTrans(List<CommandInfo> comList) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlTransaction trans = conn.BeginTransaction(); SqlCommand cmd = BuilderCommand(conn, "", 1, trans); try { int count = 0; for (int i = 0; i < comList.Count; i++) { cmd.CommandText = comList[i].CommandText; if (comList[i].IsProc) cmd.CommandType = CommandType.StoredProcedure; else cmd.CommandType = CommandType.Text; if (comList[i].Paras.Length > 0) { cmd.Parameters.Clear();//记得清空,一定要记住 foreach (var p in comList[i].Paras) { cmd.Parameters.Add(p); } } count += cmd.ExecuteNonQuery(); } trans.Commit(); return true; } catch (Exception ex) { trans.Rollback(); throw new Exception("执行事务出现异常", ex); } } } //public static T ExecuteSql<T>(string sql, int cmdType, DbParameter[] paras, Func<IDbCommand, T> action) //{ // using (DbConnection conn = new SqlConnection(connStr)) // { // conn.Open(); // IDbCommand cmd = conn.CreateCommand(); // cmd.CommandText = sql; // if (cmdType==2) // cmd.CommandType = CommandType.StoredProcedure; // return action(cmd); // } //} /// <summary> /// 比如添加一个商品表的同时,相关联的要更新其他表中的商品信息的时候,用这种方法 /// </summary> /// <typeparam name="T">委托类型:要执行的操作当做参数</typeparam> /// <param name="action"></param> /// <returns></returns> public static T ExecuteTrans<T>(Func<IDbCommand, T> action) { using (IDbConnection conn = new SqlConnection(connStr)) { conn.Open(); IDbTransaction trans = conn.BeginTransaction(); IDbCommand cmd = conn.CreateCommand(); cmd.Transaction = trans; return action(cmd); } } /// <summary> /// 构建SqlCommand /// </summary> /// <param name="conn">数据库连接对象</param> /// <param name="sql">SQL语句或存储过程</param> /// <param name="comType">命令字符串的类型</param> /// <param name="trans">事务</param> /// <param name="paras">参数数组</param> /// <returns></returns> private static SqlCommand BuilderCommand(SqlConnection conn, string sql, int cmdType, SqlTransaction trans,params SqlParameter[] paras) { if (conn == null) throw new ArgumentNullException("连接对象不能为空!"); SqlCommand command = new SqlCommand(sql, conn); if (cmdType==2) command.CommandType = CommandType.StoredProcedure; if (conn.State == ConnectionState.Closed) conn.Open(); if (trans != null) command.Transaction = trans; if (paras != null && paras.Length > 0) { command.Parameters.Clear(); command.Parameters.AddRange(paras); } return command; } } }
2,与数据库访问类中有关的事务操作的封装类:
namespace PM.DAL.Helper { /// <summary> /// 事务一系列操作中的一个操作封装类 /// </summary> public class CommandInfo { public string CommandText;//sql或存储过程名 public DbParameter[] Paras; //参数列表 public bool IsProc; //是否是存储过程 public CommandInfo() { } public CommandInfo(string comText, bool isProc) { this.CommandText = comText; this.IsProc = isProc; } public CommandInfo(string sqlText, bool isProc, DbParameter[] para) { this.CommandText = sqlText; this.Paras = para; this.IsProc = isProc; } } }
3,数据库的配置文件
<connectionStrings> <add name ="connStr" connectionString ="server=.;database=RightDBase;uid=sa;pwd=123;" providerName="System.Data.SqlClient"/> </connectionStrings>
四,通用类:字符串通用操作,类型转换等
namespace PM.Common { public static class StringHelper { /// <summary> /// 将数字字符串转换为int /// </summary> /// <param name="strValue"></param> /// <returns></returns> public static int GetInt(this string strValue) { int reInt = 0; int.TryParse(strValue, out reInt); return reInt; } public static decimal GetDecimal(this string strValue) { decimal reInt = 0; decimal.TryParse(strValue, out reInt); return reInt; } public static int GetInt(this object oValue) { int reInt = 0; try { reInt = Convert.ToInt32(oValue); } catch { reInt = 0; } return reInt; } /// <summary> /// 把字符串按照分隔符转换成 List /// </summary> /// <param name="str">源字符串</param> /// <param name="speater">分隔符</param> /// <param name="toLower">是否转换为小写</param> /// <returns></returns> public static List<string> GetStrList(this string str, char speater, bool toLower) { List<string> list = new List<string>(); string[] ss = str.Split(speater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != speater.ToString()) { string strVal = s; if (toLower) { strVal = s.ToLower(); } list.Add(strVal); } } return list; } /// <summary> /// 把字符串转 按照, 分割 换为数据 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string[] GetStrArray(this string str) { return str.Split(new Char[] { ',' }); } /// <summary> /// 把 List<string> 按照分隔符组装成 string /// </summary> /// <param name="list"></param> /// <param name="speater"></param> /// <returns></returns> public static string GetListStrToString(this List<string> list, string speater) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { if (i == list.Count - 1) { sb.Append(list[i]); } else { sb.Append(list[i]); sb.Append(speater); } } return sb.ToString(); } /// <summary> /// 得到数组列表以逗号分隔的字符串 /// </summary> /// <param name="list"></param> /// <returns></returns> public static string GetListToStr(this List<int> list) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { if (i == list.Count - 1) { sb.Append(list[i].ToString()); } else { sb.Append(list[i]); sb.Append(","); } } return sb.ToString(); } /// <summary> /// 得到数组列表以逗号分隔的字符串 /// </summary> /// <param name="list"></param> /// <returns></returns> public static string GetArrayValueStr(this Dictionary<int, int> list) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<int, int> kvp in list) { sb.Append(kvp.Value + ","); } if (list.Count > 0) { return DelLastComma(sb.ToString()); } else { return ""; } } #region 删除最后一个字符之后的字符 /// <summary> /// 删除最后结尾的一个逗号 /// </summary> public static string DelLastComma(this string str) { return str.Substring(0, str.LastIndexOf(",")); } /// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string DelLastChar(this string str, string strchar) { return str.Substring(0, str.LastIndexOf(strchar)); } #endregion /// <summary> /// 把字符串按照指定分隔符装成 List 去除重复 /// </summary> /// <param name="o_str"></param> /// <param name="sepeater"></param> /// <returns></returns> public static List<string> GetSubStringList(string o_str, char sepeater) { List<string> list = new List<string>(); string[] ss = o_str.Split(sepeater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != sepeater.ToString()) { list.Add(s); } } return list; } #region 得到字符串长度,一个汉字长度为2 /// <summary> /// 得到字符串长度,一个汉字长度为2 /// </summary> /// <param name="inputString">参数字符串</param> /// <returns></returns> public static int StrLength(string inputString) { System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); int tempLen = 0; byte[] s = ascii.GetBytes(inputString); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) tempLen += 2; else tempLen += 1; } return tempLen; } #endregion #region 截取指定长度字符串 /// <summary> /// 截取指定长度字符串 /// </summary> /// <param name="inputString">要处理的字符串</param> /// <param name="len">指定长度</param> /// <returns>返回处理后的字符串</returns> public static string ClipString(string inputString, int len) { bool isShowFix = false; if (len % 2 == 1) { isShowFix = true; len--; } System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); int tempLen = 0; string tempString = ""; byte[] s = ascii.GetBytes(inputString); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) tempLen += 2; else tempLen += 1; try { tempString += inputString.Substring(i, 1); } catch { break; } if (tempLen > len) break; } byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); if (isShowFix && mybyte.Length > len) tempString += "…"; return tempString; } #endregion public static string StringTrim(this string str) { return str.Trim(); } } }