Search code examples
c#listget

C#: Update List Item


    public class person
{
    public string name { get; set; }
    public string family { get; set; }
}

And I have a list of the same as Below:

List<person> people = new List<person>();

I want to get an item from this list that has name property equal "Afshin" and then update it.


Solution

  • First this list needs to get populated before it can be used, currently you just have an empty list.

    How the list should be populated is on you, you could manually fill it with values, (By creating new classes and add it to the list through people.Add(new person(/*person's values*/) ) or you could use a database to fill it.

    When the list is populated, you could use a Linq query:

    foreach(person p in people.Where(p => p.name.ToLower() == "afshin"))
    {
        //code to update every person who's name is "Afshin" or "afshin"
        p.family = "family of Afshin" //example
    }