How do I edit an element of this array?

Asked

Viewed 348 times

1

I have an array this way:

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 element business_Name? Can someone give me an example?

1 answer

1

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

Second, it is not possible to edit objects of anonymous types, they serve only for reading. 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; }
}

There you can create the list this way

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

From then on, you will be able to access the list by the indexes

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

Iterating on 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 understand very well why you put it loose in the question, but I advise to give a read in the answers to this question.

  • I’m on my cell phone so it’s kind of hard to write code. Anything, just comment that I fix when I have access to a computer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.