[LINQ Operators] ToList

The “ToList” operator creates a “List<T>” from a sequence.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “ToList” operator

  • NonDeferred operator
  • Purpose: Conversion

 

3. Prototypes

public static List<T> ToList<T>(this IEnumerable<T> source)

The “ToList()” operator creates a “System.Collections.Generic.List” of the type “T”. It is a nondeffered operator, which return a result right away.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var empFromCity2
  = emps.Where(e => (e.CityId==2)).ToList();

emps.Add(new Employee { Id = 100, Name = "Homer Simpson", CityId = 2 });

Console.WriteLine("Count: {0}", empFromCity2.Count); // 2

empFromCity2
  = emps.Where(e => (e.CityId == 2)).ToList();

Console.WriteLine("Count: {0}", empFromCity2.Count); // 3

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “ToList()” operator.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s