Access element in list C

C# List class represents a collection of strongly typed objects that can be accessed by index. In this tutorial, we learn how to work with lists in C# using C# List class to add, find, sort, reverse, and search items in a collection of objects using List class methods and properties.

What is C# List?

Listclass in C# represents a strongly typed list of objects. Listprovides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List, T is the type of objects.

What is the T in List?

Listclass in represents a strongly typed list of objects. Listprovides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List, T is the type of objects.

How to create List in C#?

List is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the Listclass.

  1. usingSystem.Collections.Generic;

Listclass constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object.

The code snippet in Listing 1 creates a List of Int16 and a list of string types. The last part of the code creates a Listobject with an existing collection.

  1. Listlist=newList[];
  2. Listauthors=newList[5];
  3. string[]animals={"Cow","Camel","Elephant"};
  4. ListanimalsList=newList[animals];

Listing 1.

As you can see from Listing 1, the Listhas an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands.

How to add items to a C# List?

The Add method adds an element to a List. The code snippet in Listing 2 creates two Listobjects and adds integer and string items to them respectively.

  1. ListnumberList=newList[];
  2. numberList.Add[32];
  3. numberList.Add[21];
  4. numberList.Add[45];
  5. numberList.Add[11];
  6. numberList.Add[89];
  7. Listauthors=newList[5];
  8. authors.Add["MaheshChand"];
  9. authors.Add["ChrisLove"];
  10. authors.Add["AllenO'neill"];
  11. authors.Add["NaveenSharma"];
  12. authors.Add["MonicaRathbun"];
  13. authors.Add["DavidMcCarter"];

Listing 2.

We can also add a collection to a List. The AddRange method is used to add a collection to a List. The code snippet in Listing 3 adds an array of strings to a List.

  1. string[]animals={"Cow","Camel","Elephant"};
  2. ListanimalsList=newList[];
  3. animalsList.AddRange[animals];
  4. foreach[stringainanimalsList]
  5. Console.WriteLine[a];

Listing 3.

How to read a C# List items?

List is a collection of items. We can use a foreach loop to loop through its items. The code snippet in Listing 6 reads all items of a List and displays on the console.

  1. foreach[stringainauthors]
  2. Console.WriteLine[a];

Listing 4.

The output of Listing 4 looks like Figure 1.

Figure 1.

To retrieve an item at a specific position in the List, we can use the collections index. The following code snippet reads the 3rd items in the List.

  1. Console.WriteLine[authors[2]];

How to use C# List properties

List class properties include the following:

  • Capacity Number of elements Listcan contain. The default capacity of a Listis 0.
  • Count Number of elements in List.

Code snippet in Listing 5 gets the value of these properties.

  1. ArrayListauthorsArray=newArrayList[];
  2. authorsArray.Add["MaheshChand"];
  3. authorsArray.Add["PraveenKumar"];
  4. authorsArray.Add["RajKumar"];
  5. authorsArray.Add["DineshBeniwal"];
  6. authorsArray.Add["DavidMcCarter"];
  7. Console.WriteLine["Count:"+authors.Count];
  8. Console.WriteLine["Capacity:"+authors.Capacity];

Listing 5.

How to insert elements at a position in a C# List?

The Insert method of List class inserts an object at a given position. The first parameter of the method is the 0th based index in the List.

The InsertRange method can insert a collection at the given position.

The code snippet in Listing 6 inserts a string at the 3rd position and an array at the 2nd position of the List.

  1. authors.Insert[3,"BillAuthor"];
  2. string[]newAuthors={"NewAuthor1","NewAuthor2","NewAuthor3"};
  3. authors.InsertRange[2,newAuthors];
Listing 6.

How to remove items from a C# List?

The List class provides Remove methods that can be used to remove an item or a range of items.

The Remove method removes the first occurrence of the given item in the List. The following code snippet removes the first occurrence of New Author1.

  1. authors.Remove["NewAuthor1"];

The RemoveAt method removes an item at the given position. The following code snippet removes the item at the 3rd position.

The RemoveRange method removes a list of items from the starting index to the number of items. The following code snippet removes two items starting at 3rd position.

  1. authors.RemoveRange[3,2];

The Clear method removes all items from a List. The following code snippet removes all items from a List.

How to find an element in a C# List?

The IndexOf method finds an item in a List. The IndexOf method returns -1 if there are no items found in the List.

The following code snippet finds a string and returns the matched position of the item.

  1. intidx=authors.IndexOf["NaveenSharma"];
  2. if[idx>0]
  3. Console.WriteLine[$"ItemindexinListis:{idx}"];
  4. else
  5. Console.WriteLine["Itemnotfound"];

We can also specify the position in a List where IndexOf method can start searching from.

For example, the following code snippet finds a string starting at the 3rd position in a String.

  1. Console.WriteLine[authors.IndexOf["NaveenSharma",2]];

The LastIndexOf method finds an item from the end of List.

The following code snippet looks for a string in the backward direction and returns the index of the item if found.

  1. Console.WriteLine[authors.LastIndexOf["MaheshChand"]];

The complete example is listed in Listing 7.

  1. Listauthors=newList[5];
  2. authors.Add["MaheshChand"];
  3. authors.Add["ChrisLove"];
  4. authors.Add["AllenO'neill"];
  5. authors.Add["NaveenSharma"];
  6. authors.Add["MaheshChand"];
  7. authors.Add["MonicaRathbun"];
  8. authors.Add["DavidMcCarter"];
  9. intidx=authors.IndexOf["NaveenSharma"];
  10. if[idx>0]
  11. Console.WriteLine[$"ItemindexinListis:{idx}"];
  12. else
  13. Console.WriteLine["Itemnotfound"];
  14. Console.WriteLine[authors.IndexOf["NaveenSharma",2]];
  15. Console.WriteLine[authors.LastIndexOf["MaheshChand"]];

Listing 7.

How to sort a C# List elements?

The Sort method of Listsorts all items of the List using the QuickSort algorithm.

The following code example in Listing 8 sorts a List items and displays both original order and sorted order of the List items.

  1. Listauthors=newList[5];
  2. authors.Add["MaheshChand"];
  3. authors.Add["ChrisLove"];
  4. authors.Add["AllenO'neill"];
  5. authors.Add["NaveenSharma"];
  6. authors.Add["MaheshChand"];
  7. authors.Add["MonicaRathbun"];
  8. authors.Add["DavidMcCarter"];
  9. Console.WriteLine["OriginalListitems"];
  10. Console.WriteLine["==============="];
  11. foreach[stringainauthors]
  12. Console.WriteLine[a];
  13. authors.Sort[];
  14. Console.WriteLine[];
  15. Console.WriteLine["SortedListitems"];
  16. Console.WriteLine["==============="];
  17. foreach[stringainauthors]
  18. Console.WriteLine[a];

Listing 8.

The output of Listing 8 looks like Figure 2.

Figure 2.

How to reverse a C# List elements?

The Reverse method of Listreverses the order all items in in the List.

The following code snippet reverses a List.

  1. Listauthors=newList[5];
  2. authors.Add["MaheshChand"];
  3. authors.Add["ChrisLove"];
  4. authors.Add["AllenO'neill"];
  5. authors.Add["NaveenSharma"];
  6. authors.Add["MaheshChand"];
  7. authors.Add["MonicaRathbun"];
  8. authors.Add["DavidMcCarter"];
  9. Console.WriteLine["OriginalListitems"];
  10. Console.WriteLine["==============="];
  11. foreach[stringainauthors]
  12. Console.WriteLine[a];
  13. authors.Reverse[];
  14. Console.WriteLine[];
  15. Console.WriteLine["SortedListitems"];
  16. Console.WriteLine["==============="];
  17. foreach[stringainauthors]
  18. Console.WriteLine[a];
Listing 9.

The output of Listing 9 looks like Figure 3.

Figure 3.

How to search a C# List elements?

The BinarySearch method of Listsearches a sorted list and returns the zero-based index of the found item. The Listmust be sorted before this method can be used.

The following code snippet returns an index of a string in a List.

  1. intbs=authors.BinarySearch["MaheshChand"];

Summary

This article demonstrated how to use a Listclass to work with a collection of objects. The article also demonstrated how to add, find, search, sort, and reverse items in a List.

Video liên quan

Chủ Đề