简体   繁体   中英

Changing an item in a list C#

I have an object called Cars, then a List of objects called Colours. These Colours are the posible colours the car can come with. For Example:

Car audi = new Car();
audi.Colours.Add("Black");
audi.Colours.Add("Silver");
audi.Colours.Add("White");

Now lets theoretically these could be in any order, so I can't simply use an index.

I know I can get an item using:

audi.Colours.Find(colour => colour.Name == "Silver");

How would I change the Silver item to "Swanky Diamond" without rebuilding the whole list?

In the real life situation I'm building the list from a database and I have a unique identifier.

Thanks in advance.

You can use a combination of IndexOf and a list indexer setter, like this:

var index = audi.Colours.IndexOf("Silver");
if (index >= 0) {
    audi.Colours[index] = "Swanky Diamond";
}

If the items aren't conceptually ordered then use a HashSet , rather than a List .

To see if an item is contained in the set, use Contains .

if(audi.Colours.Contains("Silver")) 
{
}

To replace one item with another remove the item you wish to remove, and add the item you wish to add:

audi.Colours.Remove("Silver");
audi.Colours.Add("Swanky Diamond");
    int zeroBasedIndex = audi.Colors.IndexOf("Silver")
if (zeroBasedIndex != -1)
    audi.Colors[zeroBasedIndex] = "Swanky Diamond";
else
    //Item Not In List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM