Created
October 1, 2013 14:31
-
-
Save vendettamit/6779430 to your computer and use it in GitHub Desktop.
Sql columns and value parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleForAnything | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Test the logic | |
// Sample array of columns and correpsonding values | |
var columnValueArray = new object[] {"Column1", "Value1", "Column2", 8, "Column3", true, "Column4", DateTime.Now }; | |
Console.WriteLine(ParametersAsSqlColumnValueMap(columnValueArray)); | |
Console.Read(); | |
} | |
/// <summary> | |
/// The parameters map for sql statements for e.g. column1 = "value1, column2 = 8 etc. | |
/// </summary> | |
/// <param name="csvColumnsValues"> | |
/// The csv columns values in ordered manner {"Column1","value1","column2",8, "column3", true"} . | |
/// </param> | |
/// <returns> | |
/// The <see cref="string"/>. | |
/// </returns> | |
private static string ParametersAsSqlColumnValueMap(params object[] csvColumnsValues) | |
{ | |
Dictionary<string, object> columnsAndValuesMap = new Dictionary<string, object>(); | |
for (int i = 0; i < (csvColumnsValues.Count() - 1); i++, i++) | |
{ | |
columnsAndValuesMap.Add(csvColumnsValues[i].ToString(), csvColumnsValues[i + 1]); | |
} | |
dynamic sql = new ExpandoObject(); | |
StringBuilder columnValueMapperBuilder = new StringBuilder(); | |
List<string> tempOrderedKeys = new List<string>(); | |
tempOrderedKeys.AddRange(columnsAndValuesMap.Keys.ToArray()); | |
foreach (var item in tempOrderedKeys) | |
{ | |
var objectValue = columnsAndValuesMap[item]; | |
var innerType = objectValue.GetType(); | |
columnValueMapperBuilder.Append(string.Format("{0}={1}", item, TypeMapperToSqlValues(innerType, objectValue))); | |
// This is to prevent the last , to be added in the columnValueMapperBuilder string | |
if ((columnsAndValuesMap.Count - 1) != tempOrderedKeys.IndexOf(item)) | |
{ | |
columnValueMapperBuilder.Append(", "); | |
columnValueMapperBuilder.Append(Environment.NewLine); // this is just for formatting. | |
} | |
} | |
return columnValueMapperBuilder.ToString(); | |
} | |
/// <summary> | |
/// The type mapper to sql values by predicting the type in the object value. | |
/// </summary> | |
private static string TypeMapperToSqlValues(Type type, object value) | |
{ | |
if (type.IsValueType && !type.IsAutoLayout) | |
{ | |
return string.Format("{0}", value); | |
} | |
else | |
{ | |
return string.Format("'{0}'", value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment