Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to update an element in a generic List [duplicate]

Suppose we have a class called Dog with two strings "Name" and "Id". Now suppose we have a list with 4 dogs in it. If you wanted to change the name of the Dog with the "Id" of "2" what would be the best way to do it?

Dog d1 = new Dog("Fluffy", "1"); Dog d2 = new Dog("Rex", "2"); Dog d3 = new Dog("Luna", "3"); Dog d4 = new Dog("Willie", "4");  List<Dog> AllDogs = new List<Dog>() AllDogs.Add(d1); AllDogs.Add(d2); AllDogs.Add(d3); AllDogs.Add(d4); 
like image 378
John H. Avatar asked Oct 09 '13 19:10

John H.


People also ask

Can list have duplicates in C#?

Place all items in a set and if the count of the set is different from the count of the list then there is a duplicate. Should be more efficient than Distinct as there is no need to go through all the list. Don't call list. Count() method.

How do I get the length of a list in C#?

Try this: Int32 length = yourList. Count; In C#, arrays have a Length property, anything implementing IList<T> (including List<T> ) will have a Count property.


2 Answers

AllDogs.First(d => d.Id == "2").Name = "some value"; 

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2"); if (dog != null) { dog.Name = "some value"; } 
like image 109
Mike Perrenoud Avatar answered Sep 21 '22 08:09

Mike Perrenoud


You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2")); 

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)     matchingDog.Name = "New Dog Name"; 
like image 43
gleng Avatar answered Sep 22 '22 08:09

gleng