Is there a function that would allow you to add an element to a List<T>
and get the index as int
back? List<T>.Add()
is a void
and does not return a value.
List.Count-1
is a solution when your are not working with threads. My list is a static member and can be accessed with multiple thread at a time and using the count-1 value is totally thread unsafe and could easily lead to wrong results.
The index will be used for specific treatment to each element.
Thank you!
To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
The Insert method is used to insert an item into the middle of the list.
Add will always insert at the end of the array, while Insert allows you to select an index. I typically prefer Add when I'm accumulating things. However if the order of the structure is important and it needs to mutate/change (for example if the new element NEEDS to be at position 4), then Insert is the way to go.
List's methods are not thread safe alone; if you just call List.Add
repeatedly from several threads you could very well run into problems. You need to use some sort of synchronization technique if you're going to use a List
in the first place, so you might as well include a call to List.Count
inside of that critical section.
Your other option would be to use a collection that is designed to be used by multiple threads, such as those in System.Collections.Concurrent
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With