LINQ Projection

just recently I have been doing quite a bit of work with LINQ and L2S in particular. Although LINQ is nothing new now and I am sure the vast majority of readers out there have had some form of introduction to LINQ. However one of the great things that I still find fascinating is a technique called projection. This is a way to shape data coming back from a query into something more akin to what you want.

   1: class User
   2: {
   3:     public string UserFullName { get; set; }
   4:     public double HoursWorked { get; set; }
   5: }
   6:  
   7: class Program
   8: {
   9:     static void Main()
  10:     {
  11:         List<User> users = new List<User>();
  12:  
  13:         users.Add(new User { HoursWorked = 12.5d, 
  14:             UserFullName = "Ann Admin" });
  15:         users.Add(new User { HoursWorked = 6.5d, 
  16:             UserFullName = "Test User" });
  17:         users.Add(new User { HoursWorked = 8.5d, 
  18:             UserFullName = "Test User" });
  19:         users.Add(new User { HoursWorked = 3.5d, 
  20:             UserFullName = "Test User" });
  21:  
  22:         var q = from user in users
  23:                 where user.UserFullName.Equals("Test User")
  24:                 select new
  25:                  {
  26:                      user.UserFullName,
  27:                      user.HoursWorked,
  28:                      HoursRemaining = (8.5 - user.HoursWorked)
  29:                  };
  30:  
  31:         foreach (var list in q)
  32:         {
  33:             Console.WriteLine(list.UserFullName + " - "
  34:                 + list.HoursWorked
  35:                 + "(" + list.HoursRemaining + ")");
  36:         }
  37:  
  38:         Console.Read();
  39:     }
  40: }

Here the query is creating a new type with three fields. This is especially useful if like above you are doing some form of calculation which you want to use, but is not represented anywhere in the data model.

1 Comment

Comments have been disabled for this content.