Get list item by id

I have a list:

List<string> theList = new List<string>; 

There are several items in the list. And now I want to get the item by index. for example I want to get item number 4. How can I do this?

+4
source share
7 answers

Just use a pointer

 string item = theList[3]; 

Note that the indices in C # are based on 0. Therefore, if you need the 4th element in the list, you need to use index 3. If you want the 5th element to use index 4. It is not clear from your question which did you intend

An indexer is a common function in .Net collection types. For lists, it is usually based on indexes; for maps, it is based on a key. The documentation for the type in question will tell you which and if it is available. The indexer member will be listed as a property named Item

http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

+9
source

To get the 4th element, you can use indexer:

 string item = theList[3]; 

if you prefer to use methods, you can use ElementAt or ( ElementAtOrDefault ):

 string item = theList.ElementAt(3); 
+4
source

You can use Indexer to get the item in the selected index

 string item = theList[3]; 
+1
source

Use index:

 string the4th = theList[3]; 

Note that this throws an exception if the list has only 3 elements or less, since the index is always based on zero. You can use Enumerable.ElementAtOrDefault , and then:

 string the4th = theList.ElementAtOrDefault(3); if(the4th != null) { // ... } 

ElementAtOrDefault returns the element at the specified index if index < list.Count and default(T) if index >= theList.Count . Therefore, for reference types (for example, String ), it returns null and for value types their default value (for example, 0 for int ).

For collection types that implement IList<T> (arrays or lists), it uses an index to get the item; for other types, it uses a foreach and a counter variable.

So, you can also use the Count property to check if the list contains enough elements for the index:

 string the4th = null; if(index < theList.Count) { the4th = theList[index]; } 
+1
source

You can use the Indexer to get the item at the selected index.

  string item = theList[3]; 

Or, if u wants to get the identifier (when accessing from the database), define a class, for example.

  public class Person { public int PId; public string PName; } 

and access as it should

  List<Person> theList = new List<Person>(); Person p1 = new Person(); int id = theList[3].PId 
+1
source

use indexer syntax :

 var fourthItem = theList[3]; 
0
source

this should do it, access through the array index.

 theList[3] 

its value 3 starts from zero.

0
source

All Articles