如何在C#中获取列表中新添加项的索引?
当我向列表中添加一个项(类的实例)时,我需要知道新项的索引。有什么功能吗 示例代码:如何在C#中获取列表中新添加项的索引?,c#,list,indexing,C#,List,Indexing,当我向列表中添加一个项(类的实例)时,我需要知道新项的索引。有什么功能吗 示例代码: MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY)); 在添加之前立即读取Count int index = MapTiles.Count; MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY)); MapTiles.Count将为您提供将添加到列表中的下
MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));
在添加之前立即读取
Count
int index = MapTiles.Count;
MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));
MapTiles.Count
将为您提供将添加到列表中的下一项的索引
比如:
Console.WriteLine("Adding " + MapTiles.Count + "th item to MapTiles List");
MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));
如果您总是使用
.Add(T)代码>方法,不使用。删除(T)
,则索引将是Count-1
MapTiles是否从列表继承?如果没有,请发布MapTiles类。否则,您的索引是MapTiles.Count-1,因为Add会附加到列表的末尾。使用.Count会更快,因为列表的大小保持在状态,但使用index对我来说似乎更正确/可读。不要使用IndexOf()
,因为它会返回对象的第一次出现。如果多次添加同一对象,请使用LastIndexOf()
。
Class1 newTile = new Class1(num, x*32 + cameraX, y*32 + cameraY);
MapTiles.Add(newTile);
int index = MapTiles.IndexOf(newTile);