Book Image

Building Interactive Queries with LINQPad

By : Sébastien Finot
Book Image

Building Interactive Queries with LINQPad

By: Sébastien Finot

Overview of this book

<p>If you need to interact with databases, XML, in-memory collections, or remote services, LINQ can make your life simpler. The best way to discover LINQ is with the help of LINQPad, a free IDE whose first goal is to make sure that writing and interacting with your LINQ query is fun and easy. More generally, LINQPad is a C#/VB/F# scratchpad that instantly executes any expression, statement block, or program with rich output formatting and a wealth of features.</p> <p>With Building Interactive Queries with LINQPad, you will quickly learn everything you need to know to start using LINQ. To accelerate your learning curve, you will discover how to use LINQPad and its features to test your queries interactively and experiment with all the options offered by LINQ.</p> <p>In all probability, you already know C#, but have you had a chance to try out LINQ? Building Interactive Queries with LINQPad will introduce you to everything LINQ can offer and will let you interact with every example in LINQPad, LINQ’s best companion.</p> <p>You will learn how to build and experiment with interactive queries with this practical guide illustrated with short and detailed code samples. You will also get acquainted with other cool applications of LINQpad such as testing, code snippet generation, and so on, along with a broad approach to LINQ (to object, to SQL, to XML, and so on).</p>
Table of Contents (14 chapters)

A LINQ query


To introduce you to LINQ, we will first look into a non-LINQ example so that we can have a point of comparison.

The standard version

We are going to implement a simple scenario: given a deck of 52 cards, we want to pick a random number of cards, and then take out all of the hearts. From this stack of hearts, we will discard the first two and take the next five cards (if possible), and order them by their face value for display.

You can try it in a C# program query in LINQPad:

public static Random random = new Random();
void Main()
{
  var deck = CreateDeck();
  var randomCount = random.Next(52);
  var hearts = new Card[randomCount];
  var j = 0;
  // take all hearts out
  for(var i=0;i<randomCount;i++)
  {
    if(deck[i].Suit == "Hearts")
    {
      hearts[j++] = deck[i];
    }
  }
  // resize the array to avoid null references
  Array.Resize(ref hearts, j);
  
   // check that we have at least 2 cards. If not, stop
  if(hearts.Length <= 2)
    return;
  var count = 0;
 ...