using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
string strID = "10010";
Dictionary<string, string> g = new Dictionary<string, string>();
g.Add("K", "k1");
g.Add("L", "l1");
string updateCustomerIncome = string.Format(" update CustomerIncome set {0} where ID = '{1}'; ",
string.Join(", ", g.Select(x => String.Format("{0} = '{1}'", x.Key, x.Value))), strID);
Console.WriteLine(updateCustomerIncome);
//var result2 = string.Join(", ", g.Select(x => String.Format("{0} = '{1}'", x.Key, x.Value)));
//Console.WriteLine(result2);
//Console.WriteLine(string.Join(", ", new List<string>(g.Keys)));
//Console.WriteLine(string.Join(", ", new List<string>(g.Values)));
string insertCustomerIncome = string.Format(" insert CustomerIncome(ID, {0}) values ('{1}', '{2}');",
string.Join(", ", new List<string>(g.Keys)), strID, string.Join("', '", new List<string>(g.Values)));
Console.WriteLine(insertCustomerIncome);
StringBuilder sb = new StringBuilder();
sb.AppendFormat("if exists (select * from CustomerIncome where id = '{0}')", strID);
sb.AppendLine();
sb.AppendLine(updateCustomerIncome);
sb.AppendLine("else");
sb.Append(insertCustomerIncome);
Console.WriteLine(sb.ToString());
}
}
the output
update CustomerIncome set K = 'k1', L = 'l1' where ID = '10010';
insert CustomerIncome(ID, K, L) values ('10010', 'k1', 'l1');
if exists (select * from CustomerIncome where id = '10010')
update CustomerIncome set K = 'k1', L = 'l1' where ID = '10010';
else
insert CustomerIncome(ID, K, L) values ('10010', 'k1', 'l1');
references:
https://dotnetfiddle.net/uiFWXo
How to get the list of key in dictionary