Conversion Operators
ToArray
This sample uses ToArray to immediately evaluate a sequence into an array.
Code:
public void Linq54()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var sortedDoubles = doubles.OrderByDescending(d => d);
var doublesArray = sortedDoubles.ToArray();
Log.WriteLine("Every other double from highest to lowest:");
for (int d = 0; d < doublesArray.Length; d += 2)
{
Log.WriteLine(doublesArray[d]);
}
}
Result:
ToList
This sample uses ToList to immediately evaluate a sequence into a List
.
Code:
public void Linq55()
{
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w
select w;
var wordList = sortedWords.ToList();
Log.WriteLine("The sorted word list:");
foreach (var w in wordList)
{
Log.WriteLine(w);
}
}
Result:
ToDictionary
This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.
Code:
public void Linq56()
{
var scoreRecords = new[] {
new {Name = "Alice", Score = 50},
new {Name = "Bob" , Score = 40},
new {Name = "Cathy", Score = 45}
};
var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Log.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
}
Result:
OfType
This sample uses OfType to return only the elements of the array that are of type double.
Code:
public void Linq57()
{
object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 };
var doubles = numbers.OfType();
Log.WriteLine("Numbers stored as doubles:");
foreach (var d in doubles)
{
Log.WriteLine(d);
}
}
Result: