[英]Changing an item in a list C#
I have an object called Cars, then a List of objects called Colours. 我有一个名为Cars的对象,然后有一个名为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? 如何在不重建整个列表的情况下将Silver项目更改为“ Swanky Diamond”?
In the real life situation I'm building the list from a database and I have a unique identifier. 在现实生活中,我正在从数据库中构建列表,并且我拥有唯一的标识符。
Thanks in advance. 提前致谢。
If the items aren't conceptually ordered then use a HashSet
, rather than a List
. 如果这些物品在概念上没有排序,请使用
HashSet
而不是List
。
To see if an item is contained in the set, use Contains
. 要查看集合中是否包含某项,请使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.