How to set value for property of an anonymous object?

后端 未结 8 898
心在旅途
心在旅途 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: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
    {
        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;
    }
    

提交回复
热议问题