how to convert :
A List :
var list = new List<string>(){"str1","str2"}
to a anonymous object :
var anonymousObject = new {str1 = "str1",str2 = "str2"}
during runtime
You can use the ExpandoObject which will give you the feature of dynamic type.
var list = new List<string>() { "str1", "str2" };
ExpandoObject obj = new ExpandoObject();
var store = (IDictionary<string, object>)obj;
list.ForEach(x => store.Add(x, x));
dynamic lst = obj;
var val = lst.str1; // Test
You can also use extension method represented below (from here).
Because converting list to dynamic object by iterating on items manually can be painful when there is many situations like this in your application.
You can use this extension method like this:
dynamic list = new List<string>() { "str1", "str2" }
.ToDictionary(dd => dd, dd => (object)dd)
.ToExpando();
The extension method:
public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary)
{
var expando = new ExpandoObject();
var expandoDic = (IDictionary<string, object>)expando;
// go through the items in the dictionary and copy over the key value pairs)
foreach (var kvp in dictionary)
{
// if the value can also be turned into an ExpandoObject, then do it!
if (kvp.Value is IDictionary<string, object>)
{
var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando();
expandoDic.Add(kvp.Key, expandoValue);
}
else if (kvp.Value is ICollection)
{
// iterate through the collection and convert any strin-object dictionaries
// along the way into expando objects
var itemList = new List<object>();
foreach (var item in (ICollection)kvp.Value)
{
if (item is IDictionary<string, object>)
{
var expandoItem = ((IDictionary<string, object>)item).ToExpando();
itemList.Add(expandoItem);
}
else
{
itemList.Add(item);
}
}
expandoDic.Add(kvp.Key, itemList);
}
else
{
expandoDic.Add(kvp);
}
}
return expando;
}
Related
I have to send a variables Json to Mailgun but it only accepts the curly braces format when using multi level json files. So,
How can I pass from this:
{ "vehicle.type": "car"}
To this, with C#
{"vehicle": {"type": "car"}}
Having into consideration that sometimes it could be up to 3 nested elements. Like element1.element2.element3: value
Here is what I recommend.
note: I am using the Newtonsoft.Json library available via Nuget, if you are using .NET Core, you can use the built in System.Text.Json library.
Because we have multiple properties in the object with flattened property keys, qualified with .s and we need to convert these properties into a hierarchical, nested JSON structure, merging siblings appropriately at each level, a simple string replacement is neither safe nor effective.
Therefore, the approach here will be to parse the flattened property keys, such as "hospital.hospitalExtraData1.Street" recursively inferring and creating a hierarchy of nested objects.
Let's begin
var originalJson = #"{
""hospital.Name"": ""BestOneEver"",
""hospital.Estatus"": ""Active"",
""hospital.hospitalExtraData1.Street"": ""43"",
""hospital.hospitalExtraData1.Color"": ""Blue"",
""hospital.hospitalExtraData1.hospitalExtraData2.IsExpensive"": ""No"",
""hospital.hospitalExtraData1.hospitalExtraData2.Works24Hrs"": ""Yes"",
""patient.Name"": ""Leonel Messi"",
""patient.Age"": ""23""
}";
var original = JsonConvert.DeserializeObject<IDictionary<string, object>>(originalJson);
Now we have an object model we can work with and restructure.
We will do this using recursion
var original = JsonConvert.DeserializeObject<IDictionary<string, object>>(originalJson);
IDictionary<string, object> Expand(IDictionary<string, object> input)
{
var result = new Dictionary<string, object>();
foreach (var property in input)
{
var (key, remainder) = ParseKey(property.Key);
if (!result.ContainsKey(key))
{
result[key] = remainder != null
? Expand(new Dictionary<string, object>
{
[remainder] = property.Value
})
: property.Value;
}
else if (result[key] is IDictionary<string, object> inner)
{
inner[remainder] = property.Value;
result[key] = Expand(inner);
}
else
{
result[key] = property.Value;
}
}
return result;
}
(string key, string remainder) ParseKey(string key)
{
var dotIndex = key.IndexOf('.');
if (dotIndex != -1)
{
return (key.Substring(0, dotIndex), key.Substring(dotIndex + 1));
}
return (key, null);
}
var expanded = Expand(original);
var expandedJson = JsonConvert.SerializeObject(expanded, Newtonsoft.Json.Formatting.Indented);
Result:
{
"hospital": {
"Name": "BestOneEver",
"Estatus": "Active",
"hospitalExtraData1": {
"Street": "43",
"Color": "Blue",
"hospitalExtraData2": {
"IsExpensive": "No",
"Works24Hrs": "Yes"
}
}
},
"patient": {
"Name": "Leonel Messi",
"Age": "23"
}
}
Here is tricky way using string replacement.
replace for any dot(.) with this (": {") and add close tag (}) at the end for every dot(.) count. Good luck!
Try This:
IDictionary<string, object> Expand(IDictionary<string, object> d)
{
var result = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> item in d)
{
var segments = item.Key.Split('.');
if (segments.Length > 1)
{
if (result.ContainsKey(segments[0]))
{
dynamic obj = new ExpandoObject();
obj = result[segments[0]];
IDictionary<string, object> myObj = obj;
myObj.Add(string.Join(".", segments.Skip(1)), item.Value);
result[segments[0]] = Expand(myObj);
}
else
{
result[segments[0]] = Expand(new Dictionary<string, object>
{
[string.Join(".", segments.Skip(1))] = item.Value
});
}
}
else
{
result[segments[0]] = item.Value;
}
}
return result;
}
I need to write search based on following criteria:
I need to find all records that match values of
key1 OR key2 OR key 3 values...etc
The number of keys and values is variable
List<KeyValuePair<string, string[]>> filterlist = new List<KeyValuePair<string, string[]>>()
{
new KeyValuePair<string, string[]>("Key1", new []{"jay","bloggs"}),
new KeyValuePair<string, string[]>("Key2", new []{"joe","blog","doe"}),
new KeyValuePair<string, string[]>("Key3", new []{"jon","blog"}),
};
Now my implementation
My current implementation does search but all expressions are "AND" instead of OR. I am not sure how to write it.
public class UserSearcher
{
private List<UserProfile> userProfiles;
public UserSearcher()
{
userProfiles = new List<UserProfile>();
}
public static List<UserProfile> SearchProfiles(List<KeyValuePair<string, string[]>> filterList)
{
var list = new List<UserProfile>();
var query = list.AsQueryable();
// search for each pair inside as or
foreach (KeyValuePair<string, string[]> searchPair in filterList)
{
foreach (string searchString in searchPair.Value)
{
string s = searchString;
// search for each item inside as and (has to contains all search strings
query = query.Where(x => x.PersonName.Contains(s));
}
}
return list = query.ToList();
}
}
The full example except db is:
https://gist.github.com/cpoDesign/acf69bc242ed0755597d
Use Predicate Builder - it works well.
So, if I got it right, you want to get back list of UserProfile where PersonName is inside any string[] of KeyValuePair list.
If so, try with this:
public static List<UserProfile> SearchProfiles(List<KeyValuePair<string, string[]>> filterList)
{
var list = new List<UserProfile>();
return list.Where(profile => filterList.Any(kvp => kvp.Value.Contains(profile.PersonName))).ToList();
}
Test example:
public static Expression<Func<T,bool>>
Or<T>(IEnumerable<Expression<Func<T,bool>>> expList){
ParameterExpression pe = Expression.Parameter(typeof(T));
Expression r = null;
foreach(var exp in expList){
r = r == null ? exp : Expression.Or(r,exp);
}
return Expression.Lambda<Func<T,bool>>(r.Body,pe);
}
var orList = new List<Expression<Func<T,bool>>>();
foreach (KeyValuePair<string, string[]> searchPair in filterList)
{
foreach (string searchString in searchPair.Value)
{
string s = searchString;
// search for each item inside as and
// (has to contains all search strings
orList.Add(x => x.PersonName.Contains(s));
}
}
query = query.Where( Or(expList));
I have to add new properties in expando object in foreach loop but I am not able to see a way to do it. Here is the example:
var allProperties = new List { "Name", "Email", "Roles" };
allProperties.AddRange(metaDataModel.GetFormattedFolders());
dynamic expando = new ExpandoObject();
foreach (var s in allProperties)
{
expando.s = string.Empty;
}
It consider 's' as a property instead of considering value of 's' as property name.
Thanks
var expando = new ExpandoObject() as IDictionary<string, Object>;
foreach (var s in allProperties)
{
expando.Add(s, string.Empty);
}
I have a dynamic object whose property begins with number. How to access this property?
For inst:
myResult.123; // this is unvalid
Any helps would be very appreciated.
If you are using ExpandoObject for your dynamic object, you can cast to IDictionary<string, object> and use an indexer;
dynamic expando = new ExpandoObject();
var dict = (IDictonary<string, object>)expando;
dict["123"] = 2;
Many other dynamic object implementations (e. g. JObject in Json.NET) provide similar functionality.
Here's an example with JObject:
var json = JsonConvert.SerializeObject(new Dictionary<string, object> { { "123", 10 } });
var deserialized = JsonConvert.DeserializeObject<object>(json);
// using the IDictionary interface
var ten = ((IDictionary<string, JToken>)deserialized)["123"].Value<JValue>().Value;
Console.WriteLine(ten.GetType() + " " + ten); // System.Int64 10
// using dynamic
dynamic d = deserialized;
Console.WriteLine(d["123"].Value.GetType() + " " + d["123"].Value); // System.Int64 10
Modified
Type t = myResult.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (PropertyInfo prp in props)
{
object value = GetPropValue(myResult, prp.Name);
dict.Add(prp.Name, value);
}
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
i have this
dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;
so , i know that d will have a property Name. Now if i don't know the name of the property at compile time , how do i add that property to the dynamic.
i found this SO Question
so, there is this complicated concept of call binders etc..which is tough to get in the first place.any simpler way of doing this ?
dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1
Here is a cleaner way
var myObject = new ExpandoObject() as IDictionary<string, Object>;
myObject.Add("Country", "Ireland");
You can also do like this:-
Dictionary<string,object> coll = new Dictionary<string,object>();
coll.Add("Prop1","hello");
coll.Add("Prop2",1);
System.Dynamic.ExpandoObject obj = dic.Expando();
//You can have this ext method to better help
public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>>
dictionary)
{
var expando = new ExpandoObject();
var expandoDic = (IDictionary<string, object>)expando;
foreach (var item in dictionary)
{
expandoDic.Add(item);
}
return expando;
}