How do I edit an element of this array?

1

I have an array like this:

List<dynamic> business_list = new List<dynamic>();

business_list.Add(new {
    business_Name = reader.GetString("name"),
    business_OwnerID = reader.GetInt32("owner_id")
});
List business_list = new List(); 

business_list.Add(new {
    business_Name = reader.GetString("name"), 
    business_OwnerID = reader.GetInt32("owner_id")
});

How can I edit the business_Name element? Can someone give me an example?

    
asked by anonymous 07.06.2017 / 04:22

1 answer

1

First, you should use a generic list. Non-generic collections are deprecated.

Second, you can not edit objects of anonymous types, they are read-only. That is, if you want to edit some property it is better to create a class.

public class Business
{
    public string Name { get; set; }
    public string OwnerId { get; set; }
}

Then you can create the list in this way

var list = new List<Business>();
list.add(new Business 
         { 
             Name = reader.getString("name"), 
             OwnerId = reader.getString("owner_id") 
          });

From there, you'll be able to access the list by indexes

var business = list[0];
business.Name = "Novo Nome";

Iterating the elements

foreach(var business in list) 
{  
    business.Name = "Novo Nome";
}

Or even using LINQ

var business = list.FirstOrDefault(b => b.Name == "Nome Antigo");
business.Name = "Novo Nome";

About the dynamic list: I did not quite understand why you put it in question, but I'd advise you to read in the answers of this question.

    
07.06.2017 / 05:10