[LINQ Operators] ToArray

The “ToArray” operator creates an array from a sequence.

 

1. Sample Data Object

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

 

2. “ToArray” operator

  • NonDeferred operator
  • Purpose: Conversion

 

3. Prototypes

public static T[] ToArray<T>(this IEnumerable<T> source)

The “ToArray()” operator creates an array of the type “T”. It is a nondeffered operator, which returns the result right away.

 

4. Example 1 (Standard Operator)

var intVals = new List<int>() { 1, 2, 3, 4, 5, 6 };

int[] oddNums
  = intVals.Where(i => (i%2 == 1)).ToArray();

intVals.Add(7);

// note that it's not 4
Console.WriteLine("Count: {0}", oddNums.Length); // 3

oddNums
  = intVals.Where(i => (i % 2 == 1)).ToArray();

Console.WriteLine("Count: {0}", oddNums.Length); // 4

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “ToArray()” 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