dev_JORD
dev_JORD

Reputation: 110

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.

Upvotes: 1

Views: 263

Answers (3)

Servy
Servy

Reputation: 203812

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");

Upvotes: 1

Josh
Josh

Reputation: 760

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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";
}

Upvotes: 10

Related Questions