this is my code for example:
var output = new
{
NetSessionId = string.Empty
};
foreach (var property in output.GetType().GetProperties())
{
property
An easy way could be to serialize the anonymous object in a Json with NewtonSoft'JsonConverter (JsonConvert.SerializeObject(anonObject)
). Then you can change the Json via string manipulation and reserialize it into a new anonymous object that you can assign to the old variable.
A little convolute but really easy to understand for beginners!
If you ever come across a situation where you need a mutable type, instead of messing around with the Anonymous
type, you can just use the ExpandoObject
:
Example:
var people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Doe" },
new Person { FirstName = "Bob", LastName = "Saget" },
new Person { FirstName = "William", LastName = "Drag" },
new Person { FirstName = "Richard", LastName = "Johnson" },
new Person { FirstName = "Robert", LastName = "Frost" }
};
// Method syntax.
var query = people.Select(p =>
{
dynamic exp = new ExpandoObject();
exp.FirstName = p.FirstName;
exp.LastName = p.LastName;
return exp;
}); // or people.Select(p => GetExpandoObject(p))
// Query syntax.
var query2 = from p in people
select GetExpandoObject(p);
foreach (dynamic person in query2) // query2 or query
{
person.FirstName = "Changed";
Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}
// Used with the query syntax in this example, but may also be used
// with the method syntax just as easily.
private ExpandoObject GetExpandoObject(Person p)
{
dynamic exp = new ExpandoObject();
exp.FirstName = p.FirstName;
exp.LastName = p.LastName;
return exp;
}