Silverlight Related Skills – Post 1

Recently I wrote that there are a number of readers who are running into difficulty with skills needed for intermediate or advanced Silverlight development that are not strictly part of Silverlight.  This is the first of an occasional series that will demonstrate these skills and techniques. 

The usual caveats apply: nothing substitutes for a good book. 

Syllogism
Major Premise: Nothing is better than a good book. 
Minor Premise: This column is better than nothing.
Conclusion: This column is better than a good book (?)

The two technologies that I’ve been running into the most as a Silverlight programmer that seem to be causing the most confusion are REST and Linq. The former is a software architecture that is loosely (some would say incorrectly) used to describe a simple web service interface over HTTP that does not have a messaging layer such as SOAP. I’ll be returning to this, but if you can’t wait, do check out John Papa’s blog entry which is short but very good (his book is great).

Linq is a more natural place for me to start as it is part of C# 3 (and I have two books on the topic <shameless plug> Learning C# 3 (this month) and Programming C# 3 and of course there are a number of excellent other books on the market that cover this material as well.

Preface

The key things to know about Linq are that it

  • is a part of the C# language, not an add-on
  • is fully object oriented and type safe
  • allows you to query any type of collection (not just databases)
  • is pronounced like a link in a chain, and stands for Language INtegrated Query.

In addition to the fundamentals of Linq, the .NET 3.5 framework has added four important class libraries:

If you want in-depth coverage of Linq, you’ll want to bookmark the LINQ project page.

Linq To Objects is the general term for using LINQ to query collections that support IEnumerable or IEnumerable<T>. We’ll start there.

Linq To SQL is a framework that supports using LINQ to query databases and we’ll look at a subset of this for querying SQLServer in coming blog entries.

The Linq To XML Class Hierarchy supports using LINQ to interact with XML elements and allows you to expand your data interaction well beyond traditional relational databases.

Linq To Entities supports using LINQ to query the Entity Data Model produced by the ADO.NET Entity Framework. I don’t expect to cover this for quite a while, but we will return to it.

Linq 101

To get started, we’ll create a very simple class that we can place in collections and then search for instances of,

 public class President
 {
   public string FirstName { get; set; } 
   public string LastName { get; set; } 
   public string TookOffice { get; set; }
 }

We begin the program by creating a collection of the first five presidents, using C# 3’s new object initialization (we could just as easily have given the class a constructor).

private List<President> presidents = new List<President>
{
   new President() { FirstName = "George", 
        LastName = "Washington", TookOffice="1789"},
   new President() { FirstName = "John",   
        LastName = "Adams",      TookOffice="1797"},
   new President() { FirstName = "Thomas", 
        LastName = "Jefferson",  TookOffice="1801"},
   new President() { FirstName = "James",  
        LastName = "Madison",    TookOffice="1809"},
   new President() { FirstName = "James",  
        LastName = "Monroe",     TookOffice="1817"}
};

The next step is to create the Linq statement, which consists of the from clause, the filtering clause and the projection.

The From Clause

The From Clause specifies the data source (in this case the presidents collection) and the range variable. A range variable is very much like an iteration variable in a foreach loop, iterating over the data source. The common idiom would be to write

from president in presidents

and the type of president would be inferred from the fact that it will be ranging over the collection presidents which is of type List<Presidents> and thus will be assigned the type President.

Note

If you find this use of the singular, plural and type name confusing, you of course are free to change the collection definition to

private List<President> chiefExecutives = new <President>
{ //...}

from thisLeader in chiefExecutives 

Some would find this less confusing, some more. The compiler doesn’t much care either way.

The Filtering Clause

The filtering clause is the where clause and is nearly identical to the where clause in Sql and is entirely optional.  The filter is a Boolean expression, but need not be a simple equality statement, you are free to set up as complex a statement as you choose. We’ll look for presidents whose first name begins with the letter J and so our filter looks like this:

where president.FirstName.StartsWith( “J” )

The Projection

Database geeks call the select statement the “projection” and it is here that you designate which properties you want to select and which objects you want to select them from. In our case, we’ll select the entire president object, and so we don’t need to designate specific properties.

select president.

Our complete Linq statement is thus

from president in presidents
where president.FirstName.StartsWith( "J" )
select president

This returns an IEnumerable<President> and thus serves well as the ItemSource for our datagrid. 

The entire source for Page.xaml.cs follows,

using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Linq;

namespace LinqDemo1
{
  public partial class Page : UserControl
  {
    private List<President> presidents = new List<President> { 
      new President() { FirstName = "George", 
        LastName = "Washington", TookOffice = "1789" }, 
      new President() { FirstName = "John", 
        LastName = "Adams", TookOffice = "1797" }, 
      new President() { FirstName = "Thomas", 
        LastName = "Jefferson", TookOffice = "1801" }, 
      new President() { FirstName = "James", 
        LastName = "Madison", TookOffice = "1809" }, 
      new President() { FirstName = "James", 
        LastName = "Monroe", TookOffice = "1817" } }; 
    
    public Page() 
    { 
      InitializeComponent(); 
      Loaded += new RoutedEventHandler( Page_Loaded ); 
    }

    void Page_Loaded( object sender, RoutedEventArgs e )
    {
      LinqStatement.Text = @"from president in presidents            
        where president.FirstName.StartsWith( ""J"" )            
        select president"; 
      
      Results.ItemsSource = from president in presidents 
                            where president.FirstName.StartsWith( "J" ) 
                            select president;
    }
  }
}

The display is equally simple, offering a text box to show the Linq statement and a DataGrid for the results,

LinqDemo1

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.