LINQ Conversion Operators (ToArray,ToList,ToDictionary,OfType)
ToArray
This sample uses ToArray to immediately evaluate a sequence into an array.
ToList
This sample uses ToList to immediately evaluate a sequence into a List<T>.
ToDictionary
This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.
OfType
This sample uses OfType to return only the elements of the array that are of type double.
This sample uses ToArray to immediately evaluate a sequence into an array.
static void Main(string[] args) { double[] doubles = { 2.2, 1.3, 2.0, 4.1, 2.3 }; 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 = 0; d < doublesArray.Length; d += 2) { Console.WriteLine(doublesArray[d]); } Console.ReadKey(true); }Output
ToList
This sample uses ToList to immediately evaluate a sequence into a List<T>.
static void Main(string[] args) { string[] words = { "cherry", "banana", "apple", "blueberry", "watermelon", "grape" }; 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); } Console.ReadKey(true); }Output
ToDictionary
This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.
static void Main(string[] args) { var scoreRecords = new[] { new {Name = "Parthiv Patel", Score = 40}, new {Name = "Sachin Tendulkar" , Score = 100}, new {Name = "Yuvraj Singh", Score = 70} }; var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); Console.WriteLine("IPL's score: {0}", scoreRecordsDict["Sachin Tendulkar"]); Console.ReadKey(true); }Output
OfType
This sample uses OfType to return only the elements of the array that are of type double.
static void Main(string[] args) { object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 ,8.0}; var doubles = numbers.OfType<double>(); Console.WriteLine("Numbers stored as doubles:"); foreach (var d in doubles) { Console.WriteLine(d); } Console.ReadKey(true); }Output
LINQ Conversion Operators (ToArray,ToList,ToDictionary,OfType)
Reviewed by Bhaumik Patel
on
9:02 PM
Rating: