我有这段代码:
var parameters = new Dictionary<string, object>();
parameters.Add("param1", 100);
parameters.Add("param2", "ABC");
parameters.Add("param3", 1.2);
我需要以最大的性能生成下面的代码,可以使用Linq,Lambda等。!?
var tableName = "table1"
var fields = "param1, param2, param3";
var values = "@param1, @param2, @param3"
var result = String.Format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, fields, values);
...执行Sql AddParamWithValue ....(这没关系,我可以做到......)
答案 0 :(得分:3)
好的,所以,我做了一点测试,string.join效果很好:
param = string.Join(",", parameters.Keys);
value = string.Join(",", parameters.Values);
这是我的测试功能:
private static void RunLoopTester()
{
Console.WriteLine("Building dictionary...");
var parameters = new Dictionary<string, string>();
for(var i = 0;i< 10000;i++)
{
parameters.Add(string.Format("param{0}",i),string.Format("value{0}", i));
}
var stopWatch = new Stopwatch();
Console.WriteLine("Using foreach statement...");
stopWatch.Start();
var param = string.Empty;
var value = string.Empty;
foreach(var k in parameters.Keys)
{
param += string.Format("{0}{1}", string.IsNullOrEmpty(param) ? string.Empty : ",", k);
value += string.Format("{0}{1}", string.IsNullOrEmpty(value) ? string.Empty : ",", parameters[k]);
}
stopWatch.Stop();
Console.WriteLine("Elapsed Time: {0}", stopWatch.ElapsedMilliseconds);
Console.WriteLine("Using simple syntax...");
param = string.Empty;
value = string.Empty;
stopWatch.Reset();
stopWatch.Start();
param = string.Join(",", parameters.Keys);
value = string.Join(",", parameters.Values);
stopWatch.Stop();
Console.WriteLine("Elapsed Time: {0}", stopWatch.ElapsedMilliseconds);
Console.ReadLine();
}
结果:
Pick your tester:
1: Timer Test
2: Loop Tester
2
Building dictionary...
Using foreach statement...
Elapsed Time: 1249
Using simple syntax...
Elapsed Time: 1
编辑:接受发布。 OP提到proc参数需要@param。这可以通过将其放入字典的键(更好)或者如果不能,则可以替换:
param = string.Join(",", parameters.Keys);
使用:
param = string.Join(",", parameters.Keys).Replace("param","@param");
这会将时间增加到2毫秒。我尝试在可枚举的密钥上使用linq select,但是将时间增加到4毫秒。所以替换更有效率。