开发者

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

开发者 https://www.devze.com 2023-03-20 05:44 出处:网络
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?

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


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


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


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


Read Count immediately before adding.

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

精彩评论

暂无评论...
验证码 换一张
取 消