首页 > 代码库 > c#从基础学起string.Join(",", keys.ToArray())

c#从基础学起string.Join(",", keys.ToArray())

总感觉自己工作6年了,经验丰富。直到近期报了一个.net进阶班才知道。我还差得很远。就拿string.join对比

我的代码:

public static int InsertModel<T>(T t) where T : BaseModel        {            Type type = typeof(T);            string columnStrings = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name)));            string sql = "insert into "+type.Name+"(";            foreach (var item in type.GetProperties())            {                if (item.Name != "Id")                {                    sql+=item.Name+",";                }            }            sql = sql.Substring(0, sql.Length - 1);            sql += ")";            sql+=" values(";            foreach (var item in type.GetProperties())            {                if (item.Name != "Id")                {                    sql += "" + item.GetValue(t) + "‘,";                }            }            sql = sql.Substring(0, sql.Length - 1);            sql += ")";            return DbHelperSQL.ExecuteSql(sql);        }

会发现在insert的时候我拼接的比较辛苦,后来和我们班的优秀作业对比了一下。下面是他的代码:

 public bool Insert<T>(T t) where T : BaseModel        {            //插入实体时要判断一下时间的插入.还可以通过特性来判断一下数据的长度            //约定的id为自增长.            var type = typeof(T);            var keys = new List<string>();            var values = new List<string>();            var par = new List<SqlParameter>();            foreach (var item in type.GetProperties())            {                var value =http://www.mamicode.com/ item.GetValue(t);                if (item.Name.ToLower() == "id") continue;                keys.Add(item.Name);                values.Add("@" + item.Name);                par.Add(new SqlParameter("@" + item.Name, value));            }            var c = string.Join(",", keys.ToArray());            var v = string.Join(",", values.ToArray());            var sql = string.Format($"INSERT INTO [{type.Name}] ({c}) " +                $"VALUES({v})");            return ExcuteSql<bool>(sql, cmd =>            {                foreach (var parameter in par)                    cmd.Parameters.Add(parameter);                var result = cmd.ExecuteNonQuery();                return result > 0;            });            //   return RunCmd(sql, par.ToArray());        }

发现他很巧妙的用了string.join。与我的相比省去了好多代码

以后当自勉,代码更上一层!!!

c#从基础学起string.Join(",", keys.ToArray())