adding new properties in expando object in foreach loop - c#

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);
}

Related

Create c# dynamic object from elements of a list

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;
}

Append items to an object

I have created a Linq statement to get a list of items from the database. So I need to loop trough the query and append to object to then serialize to then be able to use as json in javascript. The problem is I cannot append to the declared object 'obj'. Can anyone help??
DataContext dataContext = new DataContext();
var query = from qr in dataContext.tblStocks
where qr.enable == true
select qr;
var obj = new JObject();
foreach (var item in query)
{
//obj = new JObject();
obj = ( new JObject(
new JProperty("stockID",item.stockID),
new JProperty("itemDepartmentID", item.itemDepartmentID),
new JProperty("item" , item.item),
new JProperty("description", item.description),
new JProperty("stockAmount", item.stockAmount),
new JProperty("priceExlVat", item.priceExlVat),
new JProperty("vat", item.vat),
new JProperty("priceIncVAT", item.priceIncVAT),
new JProperty("upc1", item.upc1),
new JProperty("upc2", item.upc2)
));
}
var serialized = JsonConvert.SerializeObject(obj);
return serialized;
You are reassigning obj each time through the loop hence all other data will be lost.
Easier to create an array:
obj = new JArray();
foreach (var item in query) {
obj.Add(new JObject(
new JProperty(...),
...));
}
Why don't you just serialize your object?
List<dynamic> obj = new List<dynamic>();
foreach(var item in query) {
obj.Add(new
{
itemDepartmentID = item.itemDepartmentID,
description = item.description,
...
});
}
var serialized = JsonConvert.SerializeObject(obj);
Alternative you could use an anonymous type in the query and just serialize the entire query for the query returns an IEnumerable<T> and this is converted automatically to an jsonArray:
DataContext dataContext = new DataContext();
var query = dataContext.tblStocks
.Where(stockItem => stockItem.enable)
.Select(stockItem => new
{
stockItem.stockID,
stockItem.itemDepartmentID,
stockItem.item,
stockItem.description,
stockItem.stockAmount,
stockItem.priceExlVat,
stockItem.vat,
stockItem.priceIncVat,
stockItem.upc1,
stockItem.upc2
});
return JsonConvert.SerializeObject(query);

Dynamic object property name begins with number

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);
}

property.GetValue(dynamictype,null) throw RuntimeBinderException

I have a dynamic type object and I want to get all the values of every property from the object.
dynamic row = ....
I am using property.GetValue(row, null) throws a RuntimeBinderException.
How can I retrieve this value?
This will iterate thru all public properties:
dynamic something = new {id = "1", name = "name"};
Type type = something.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
var value = property.GetGetMethod().Invoke(something, null);
Console.WriteLine(string.Format("{0}:{1}", property.Name, value));
}

Dynamically adding properties to a dynamic object?

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;
}

Categories