List<T>


Intro

My notes on the List<T> class.

<T> represents the type of the object the list will hold. It is a strongly typed list of objects so you will only be able to add objects of the type<T>.


Namespaces To Include

You need to include using System.Collections.Generic;

If you use any of the IEnumerable methods, then you need to include: using System.Linq; If you forget, then you get this error

'System.Collections.Generic.List<int>' does not contain a definition for 'Any' and no extension method 'Any' accepting a first argument of type 'System.Collections.Generic.List<int>' could be found (are you missing a using directive or an assembly reference?)


Create an empty list of strings

 

List<string> listOfStrings = new List<string>();

 


Enumerable’s Common Used Methods

The List<T> class inherits from the IEnumerable interface, which means any of the methods from that class can be used on the list. These are some of its common methods one may use.

 

.Any()

Determines whether any element of a sequence exists or satisfies a condition.

using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3 }; bool hasElements = numbers.Any(); Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); } }

Output from DotNetFiddler

 


.Select()

Select() allows you to iterate through the list and apply a function to each element. Note that function is not applied until the iteration is invoked (ie delayed execution).

Output from DotNetFiddle


IList<T> - The interface version

 

  • IList<T> is an interface, which is implemented by the List and Array types.

 

When to use IList<T> vs List<T>

 

From Stackoverflow: List<T> or IList<T>

  • If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change. If you are just using it internally, you may not care so much, and using List<T> may be ok.

 

From Stackoverflow: When to use IList and when to use List

  • Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Â