Sunday, February 7, 2010

Anonymous types - sorting & working with Linq

Consider the following code




  1.        var numbers = new int[] { 1, 4, 6, 2, 9, 10, 0, 99, 33 };

  2.             var sortedNums = from n in numbers
  3.                              orderby n descending
  4.                              select n;
  5.             foreach (var v in sortedNums)
  6.                 Console.WriteLine(v);

  7.             var sports = new string[] { "soccer", "baseball" };
  8.             var Name = from sport in sports select new { Title = sport };
  9.             foreach (var s in Name)
  10.                 Console.WriteLine(s.Title);
Line 3 sorts the array of anonymous numbers in descending order ( by default ASC is used )
Line 10 gives a new property to the the string collection created in line 9, see the new property usage in Line 12
Post a Comment