Linq101-Conversion Operators

时间:2023-03-09 23:10:29
Linq101-Conversion Operators
 using System;
using System.Linq; namespace Linq101
{
class Conversion
{
/// <summary>
/// This sample uses ToArray to immediately evaluate a sequence into an array.
/// </summary>
public void Linq54()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; //var doublesArray = doubles.OrderByDescending(d => d).ToArray();
var sortedDoubles = from d in doubles
orderby d descending
select d;
var doublesArray = sortedDoubles.ToArray(); Console.WriteLine("Every other double from highest to lowest:");
for (int d = ; d < doublesArray.Length; d += )
{
Console.WriteLine(doublesArray[d]);
}
} /// <summary>
/// This sample uses ToList to immediately evaluate a sequence into a List<T>.
/// </summary>
public void Linq55()
{
string[] words = { "cherry", "apple", "blueberry" }; //var wordList = words.OrderBy(w => w).ToList();
var sortedWords =
from w in words
orderby w
select w;
var wordList = sortedWords.ToList(); Console.WriteLine("The sorted word list:");
foreach (var w in wordList)
{
Console.WriteLine(w);
}
} /// <summary>
/// This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.
/// </summary>
public void Linq56()
{
var scoreRecords = new[] { new {Name = "Alice", Score = },
new {Name = "Bob" , Score = },
new {Name = "Cathy", Score = }
}; var scoreRecordsDict = scoreRecords.ToDictionary(s => s.Name); Console.WriteLine("Bob' Score: {0}", scoreRecordsDict["Bob"].Score);
} /// <summary>
/// This sample uses OfType to return only the elements of the array that are of type double.
/// </summary>
public void Linq57()
{
object[] numbers = { null, 1.0, "two", , "four", , "six", 7.0 }; var doubles = numbers.OfType<double>(); Console.WriteLine("Numbers stored as doubles:");
foreach (var d in doubles)
{
Console.WriteLine(d);
}
}
}
}