Getting Started With Linq

A LINQ Tutorial

If you are serious about Windows Phone programming then it is imperative to become at least familiar with LINQ.  This is given additional impetus by the emerging importance of Reactive Programming, a full understanding of which requires at least a working understanding of LINQ.

Over the next few weeks or more, I’ll explore LINQ in a series of episodic postings.  None of this is terribly difficult, though there are some syntactic bits that take a little getting used to.

Let’s start easy with a simple program that illustrates the use of Linq statements

For this example, and many others we’ll use a very simple UI consisting of two rows. In the upper, smaller row, we’ll place a TextBlock and in the lower, larger row we’ll place a ListBox.  The complete Xaml source code for the content panel is provided here,

<!--ContentPanel - place additional content here-->
<Grid
   x:Name="ContentPanel"
   Grid.Row="1"
   Margin="12,0,12,0">
   <Grid.RowDefinitions>
      <RowDefinition
         Height="1*" />
      <RowDefinition
         Height="8*" />
   </Grid.RowDefinitions>
   <TextBlock
      Name="Message"
      Text="Ready..."
      HorizontalAlignment="Center"
      VerticalAlignment="Center"
      Grid.Row="0"
      Grid.Column="0" />

   <ListBox
      Name="TheListBox"
      HorizontalAlignment="Stretch"
      VerticalAlignment="Stretch"
      Margin="10"
      Grid.Row="1"
      Grid.Column="0" />
</Grid>

The source code is in the code behind (MainPage.xaml.cs) where we create a generic list of integers, and then search through that list using a LINQ query statement,

Here’s the complete source code, let’s go through it line by line…

using System.Collections.Generic;
using System.Linq;
using Microsoft.Phone.Controls;

namespace Linq1
{
   public partial class MainPage : PhoneApplicationPage
   {
      public MainPage( )
      {
         InitializeComponent( );
         DoLinq( );
      }

      private void DoLinq( )
      {
         var list = new List<int>( )
           { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
         var query = from num in list
                     where num > 5
                     select num;
         foreach ( var num in query )
         {
            TheListBox.Items.Add( num.ToString( ) );
         }
      }
   }
}

Lines 1 and 2 add the necessary include files to use generics and to use Linq respectively.

The constructor (lines 9-13) call our working test method, DoLinq, which is implemented on lines 15-26.

On line 17 we create a generic list of integers.  You pronounce List<int> as “list of int” and the syntax indicates that this is a type-safe list; it will hold integers but nothing else.  The name of the variable that this list is assigned to is list, and its type is not var.

Note the new initialization syntax. Again, this is a convenience feature; though this could have been written as,

 var list = new List<int>( );
 list.Add( 1 );
 list.Add( 2 );
 list.Add( 3 );
 list.Add( 4 );
 list.Add( 5 );
 list.Add( 6 );
 list.Add( 7 );
 list.Add( 8 );
 list.Add( 9 );

with the same results.

Var is a keyword which allows the compiler to infer the type of the variable, but make no mistake, at run time this line is exactly as if you had typed

System.Collections.Generic.IEnumerable<int> list =
  new List<int>( ) { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

With our list of integers created we next set up a query to filter (where) the values we want and then to project (select) the results (lines 20-22.

The variable query is also an IEnumerable, and thus subject to iteration with a foreach loop.  We take each value in turn and add it to the list box.  You’ll notice in the list box that we retrieve only the values that were in the original list and that make it through the filter.

Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
This entry was posted in Linq, Patterns & Skills and tagged . Bookmark the permalink.

2 Responses to Getting Started With Linq

  1. Thanks for your tutorials, they have helped me a lot with linq.
    I hope to learn more and more here…

  2. Pingback: Tweets that mention Getting Started With Linq | Jesse Liberty -- Topsy.com

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>