How to set value for property of an anonymous object?

后端 未结 8 897
心在旅途
心在旅途 2020-12-05 17:44

this is my code for example:

var output = new
{
    NetSessionId = string.Empty
};

foreach (var property in output.GetType().GetProperties())
{
    property         


        
相关标签:
8条回答
  • 2020-12-05 18:20

    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!

    0 讨论(0)
  • 2020-12-05 18:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题