Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element to List<T> and get the index back?

Tags:

c#

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!

like image 522
Moslem Ben Dhaou Avatar asked Oct 17 '12 14:10

Moslem Ben Dhaou


People also ask

How do you get an index of an element in a list C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.

Does list have index C#?

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.

What does list insert Do C#?

The Insert method is used to insert an item into the middle of the list.

What is the difference between the Add method and the insert method of a list object?

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.


1 Answers

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.

like image 139
Servy Avatar answered Sep 18 '22 15:09

Servy