Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中获取列表中新添加项的索引?_C#_List_Indexing - Fatal编程技术网

如何在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);