Skip to content

Instantly share code, notes, and snippets.

@deepumi
Created January 17, 2017 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepumi/08e73e22403203adf7fe6ab6de53f449 to your computer and use it in GitHub Desktop.
Save deepumi/08e73e22403203adf7fe6ab6de53f449 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.ComponentModel;
public class DictionaryParameter
{
private readonly Dictionary<string, object> _parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public DictionaryParameters(object param)
{
if (param == null) return;
AddValues(param);
}
public IDictionary<string, object> Parameters => _parameters;
private void AddValues(object values)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
{
Add(descriptor.Name, descriptor.GetValue(values));
}
}
public void Add(string key, object value)
{
_parameters.Add($"@{key}", value);
}
}
public static class KeyValueParameterExtensions
{
//Another apporach using Lazy pattern IEnumerable<KeyvVluePair<string,object>>
public static IEnumerable<KeyValuePair<string, object>> ToKeyValueList(this object param)
{
if (param == null) yield break;
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(param))
{
yield return new KeyValuePair<string, object>($"@{descriptor.Name}", descriptor.GetValue(param));
}
}
}
ex :
var param = new {ApplicationName = "FFF",minDate = "ff",Another = 1,CreateDate = DateTime.Now,ABC = Guid.NewGuid(),AnotherGuid = Guid.NewGuid()}.ToKeyValueList();
var dict = new DictionaryParameters(new {ApplicationName = "FFF",minDate = "ff",Another = 1,CreateDate = DateTime.Now,ABC = Guid.NewGuid(),AnotherGuid = Guid.NewGuid()}.ToKeyValues());
var dictParameters = dict.Parameters;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment