101 LINQ Samples: Conversion Operators

ToArray

This sample uses ToArray to immediately evaluate a sequence into an array.


     
       
  1. public void Linq54()
  2. {
  3.     double[] doubles = { 1.72.31.94.12.9 };
  4.  
  5.     var sortedDoubles =
  6.         from d in doubles
  7.         orderby d descending
  8.         select d;
  9.     var doublesArray = sortedDoubles.ToArray();
  10.  
  11.     Console.WriteLine("Every other double from highest to lowest:");
  12.     for (int d = 0; d < doublesArray.Length; d += 2)
  13.     {
  14.         Console.WriteLine(doublesArray[d]);
  15.     }
  16. }

Result

Every other double from highest to lowest:
4.1
2.3
1.7

ToList

This sample uses ToList to immediately evaluate a sequence into a List<T>.


     
       
  1. public void Linq55()
  2. {
  3.     string[] words = { "cherry""apple""blueberry" };
  4.  
  5.     var sortedWords =
  6.         from w in words
  7.         orderby w
  8.         select w;
  9.     var wordList = sortedWords.ToList();
  10.  
  11.     Console.WriteLine("The sorted word list:");
  12.     foreach (var w in wordList)
  13.     {
  14.         Console.WriteLine(w);
  15.     }
  16. }

Result

The sorted word list:
apple
blueberry
cherry

ToDictionary

This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.


     
       
  1. public void Linq56()
  2. {
  3.     var scoreRecords = new[] { new {Name = "Alice", Score = 50},
  4.                                 new {Name = "Bob"  , Score = 40},
  5.                                 new {Name = "Cathy", Score = 45}
  6.                             };
  7.  
  8.     var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
  9.  
  10.     Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
  11. }

Result

Bob's score: { Name = Bob, Score = 40 }

OfType

This sample uses OfType to return only the elements of the array that are of type double.


     
       
  1. public void Linq57()
  2. {
  3.     object[] numbers = { null1.0"two"3"four"5"six"7.0 };
  4.  
  5.     var doubles = numbers.OfType<double>();
  6.  
  7.     Console.WriteLine("Numbers stored as doubles:");
  8.     foreach (var d in doubles)
  9.     {
  10.         Console.WriteLine(d);
  11.     }
  12. }

Result

Numbers stored as doubles:
1
7

你可能感兴趣的:(conversion)