dynamic - c# initialize expandoobject from list<T> -


i want initialize expandoobject list.

internal class carkeyvalue {     public carkey carkey { get; set; }     public string value1 { get; set; }     public string value2 { get; set; } }  public enum carkey {     brand = 1,     model = 2,     year = 3,     factorylocation = 4,     //more 400 key here... }  var car = new list<carkeyvalue>{     new carkeyvalue {carkey = carkey.brand, value1 = "ford"},     new carkeyvalue {carkey = carkey.model, value1 = "focus",value2 = "titanium"},     new carkeyvalue {carkey = carkey.year, value1 = "1995"},     new carkeyvalue {carkey = carkey.factorylocation, value1 = "turkey",value2="bursa"},         };  dynamic expando = new expandoobject(); foreach(var item in car){     expando.[item.carkey].value1 = item.value1; //incorrect primary expression.     expando.[item.carkey].value2 = item.value2; } 

how that? need use expando object. try use idictionary<string,dynamic> thrown exception.

is there possible way?

yes, can, makes no sense. have cast expando object idictionary<string, object> or idictionary<string, dynamic>.

idictionary<string, object> expando = new expandoobject(); foreach (var item in car) {     expando[item.carkey.tostring()].value1 = item.value1; } 

the above code fails because never assign value expando[item.carkey.tostring()]. instead want set property non-existing object. regular code have thrown nullreferenceexception here. (you can read above code expando.someproperty.value1, someproperty null.)

so once have set object instance of something, can use it, there not use in using expandoobject more:

foo foo = new foo(); expando[item.carkey.tostring()] = foo; foo.value1 = item.value1; 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -