How do I get the index of a newly added item in a list in C#?

筅森魡賤 提交于 2019-12-18 06:53:33

问题


When I add an item (an instance of a class) to a list, I need to know the index of the new item. Is it possible with any function?

Example code:

MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));

回答1:


MapTiles.Count will give you the index of next item that will be added to the list

Something like:

Console.WriteLine("Adding " + MapTiles.Count + "th item to MapTiles List");
MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));



回答2:


Class1 newTile = new Class1(num, x*32 + cameraX, y*32 + cameraY);
MapTiles.Add(newTile);
int index = MapTiles.IndexOf(newTile);



回答3:


Read Count immediately before adding.

int index = MapTiles.Count;
MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY));



回答4:


If you're always using the .Add(T); method and not using .Remove(T);, then the index will be Count - 1.



来源:https://stackoverflow.com/questions/6701225/how-do-i-get-the-index-of-a-newly-added-item-in-a-list-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!