LINQPad – Cool Utility For LINQ

Maybe you know about this, but I saw it first few days a go. I feel in love.linqpadlogo

LINQPad is a cool little utility that was mainly created to allow you to test LINQ expressions and see them produce a  result and output the results in a nice easy to visualize format. It’s great for running LINQ Queries without having to fire up Visual Studio.

LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book,"C# 3.0 in a Nutshell" written by Joseph Albahari, the author of LINQPad.  There’s no better way to experience the coolness of LINQ and functional programming.

LINQPad is more than just a LINQ query tool: it’s a code snippet IDE. Instantly execute any C# 3 or VB 9 expression or statement block! LINQPad does a great job at LINQ execution and visualization, but it has a lot more uses than just a LINQ query tool. It’s basically a snippet editor that allows you to save snippets and more importantly, execute just about any code that you can write as an expression or single function block.

For example, LINQ to SQL results:


Output can be displayed both as a result table view, the raw SQL (from .ToString()) and a useful code conversion from the LINQ Expression syntax to LINQ command syntax using command chaining of the various LINQ extensions methods.

Other example (from the preloaded examples):


There’s no installation – it’s a single self contained EXE you can copy anywhere assuming you have .NET 3.5 installed.

Download it here.


Share this post :

Search File System Using LINQ

Do you want to search a file or file type in the file system ? Nice way to do it is using LINQ.

var files = from file in new DirectoryInfo(@"D:temp").GetFiles()
where file.Name == "MyFile.txt"
select file;

Or even search after specific file extension :

var files = from file in new DirectoryInfo(@"D:temp").GetFiles()
where file.Extension == ".txt"
select file;



LINQ in Action: Book Review

LINQ in Action Recently I got a copy of the book "LINQ in Action" (by Fabrice Marguerie, Steve Eichert, Jim Wooley, and Matt Warren (Foreword))from Manning publishing. Language Integrated Query (LINQ) is a great feature and I wrote about it in this blog.

The book targets the .NET developers who know C# (2.0) or VB.NET (8.0): Whether you don’t know LINQ or you already know – this book is for you. Read it!

For me, it was a pleasure to read it: smooth, clear, didactic and effective.

The book divided into 4 parts:

Getting started, Querying objects in memory, Querying relational data, Manipulating XML and LINQing it all together. The book starts out with a brief of LINQ and then covers the main language enhancements of C# 3.0 and VB.NET 9.0 including: Implicitly typed local variables, Object initializers, Lambda expressions, Extension methods, and Anonymous types. This is a great overview of the features!  There is also introduction covering the history of LINQ, which also presents all the problems that LINQ solves and the design goals of LINQ.

One of the things I really like in this book is that the book doesn’t just focus on LINQ to SQL. If you want to know where LINQ is required – read this book. Also, if you want deep dive into LINQ’s core – this book is for you. The great thing of this book: It’ll satisfy all developers spectrum. One of my favorites chapters in the book is the explanations about extending LINQ.

I think that the last part of the book: LINQing it all together is the best part. It’s a great summary for a great book.

The book absolutely helps you and motivate you to use the technology on your next project.

To summarize: for me, this is the only required book for learning LINQ. if you want to know LINQ and love it, you must read this book!!!

LINQ in Action – 5 stars in Maor’s index.

Pro LINQ: Language Integrated Query in C# 2008 – Early Review

LINQ I like LINQ and I posted about it in my blog.

In the last 2 weeks I have been reading the book Pro LINQ: Language Integrated Query in C# 2008  by Joseph C. Rattz, Jr.  | ISBN: 1-59059-789-3 which I have had access to via the Early Access Program as a PDF ebook.

This book provides superb coverage of LINQ where it shows the reader how to leverage all the new LINQ C# 2008 language features including extension methods, lambda expressions, anonymous data types, and partial methods.

The book refers to all kinds of LINQ including LINQ to Objects, LINQ to SQL, LINQ to XML, LINQ to DataSet. The book starts with an introduction of what LINQ is (the first and second chapters, "Hello LINQ" & "C# 3.0 Language Enhancements for LINQ") and builds this more and more throughout the book and the next chapters.  Even if you don’t a proficient C# developer, you’ll find the book useful. It provides a very good high level overview of all the sections, however goes deep into the inner works of LINQ.

The question whether to use LINQ or not is answered: the book gives you an in-depth understanding about LINQ when and where it is required. 

I like the writing style to Joseph: at eye level and very coherent.

If LINQ interesting you and you would like to know it well – I highly recommend you get this book. Once I get the final version of the book, I will give it another read.

You can download the first chapter for free:

Table of Contents

PART 1 Pro LINQ: Language Integrated Query in C# 2008
CHAPTER 2 C# 3.0 Language Enhancements for LINQ

PART 2 LINQ to Objects
CHAPTER 3 LINQ to Objects Introduction
CHAPTER 4 Deferred Operators
CHAPTER 5 Nondeferred Operators

CHAPTER 6 LINQ to XML Introduction
CHAPTER 8 LINQ to XML Operators
CHAPTER 9 Additional XML Capabilities

PART 4  LINQ to DataSet
CHAPTER 10 LINQ to DataSet Operators
CHAPTER 11 Additional DataSet Capabilities

CHAPTER 12 LINQ to SQL Introduction
CHAPTER 13 LINQ to SQL Tips and Tools
CHAPTER 14 LINQ to SQL Database Operations
CHAPTER 15 LINQ to SQL Entity Classes
CHAPTER 16 The DataContext
CHAPTER 17 Concurrency Conflicts
CHAPTER 18 Additional SQL Capabilities


Technorati Tags:

LINQBridge – Use LINQ to objects in .NET 2.0

I really like LINQ, but what if I want to use it and the target framework is not .NET 3.5? There is a way to use LINQ to Objects in .NET 2.0 projects. LINQBridge makes this possible. I saw it today but I didn’t try it yet. (I’ll be soon)

How it works?

First, it’s important to understand that C# 3.0 and Framework 3.5 are designed to work with CLR 2.0-the same CLR version that Framework 2.0 uses. This means that the C# 3.0 compiler emits IL code that runs on the same virtual machine as before.

This makes Framework 3.5 additive-just as Framework 3.0 was additive-comprising additional assemblies that enhance the existing 2.0 Framework and CLR. So there’s nothing to stop us from writing our own assemblies that do the work of Framework 3.5 (at least, the critical bits required for local LINQ queries).

Go to LINQBridge official page – you’ll find there more info as well as source code.

Technorati Tags:

Linq to XML – Adding,Updating and Deleting data

The previous post about Linq to XML introduced how to query XML data using LINQ. LINQ allows us to not only query XML in a truly unique way, but also create XML documents in a very expressive manner. This post will talk about other operations on the XML: adding, updating and deleting data.

First, lets create a sample XML document:

   1:  XElement book = new XElement("Books", new XElement("Book",
   2:      new XAttribute("publisher", "O'Reilly Media, Inc."),
   3:          new XAttribute("price", "40$"),
   4:          new XElement("title", "Learning WCF: A Hands-on Guide"),
   5:          new XElement("authors", new XElement("author", "Michele Bustamante"))));
   7:  book.Save("Books.xml");

Adding data to the XML document

Adding XML to the existing XML document is very simple, we need only construct our XML using a mixture of XElement and XAttribute types (there are other ways also…) and then add them to the document.

The following adds a new book:

   1:  XElement doc = XElement.Load("Books.xml");
   2:  XElement newBook = new XElement("Book",
   3:      new XAttribute("publisher", "Microsoft Press"),
   4:      new XAttribute("price", "45$"),
   5:      new XElement("title", "Introducing Microsoft LINQ"),
   6:      new XElement("authors", new XElement("author", "Paolo Pialorsi"), 
   7:          new XElement("author", "Marco Russo")));
   9:  doc.Add(newBook);
  10:  doc.Save("Books.xml");

We must save the xml with the save method, because in LINQ to XML, no changes are made to the loaded XML document until that document is saved.

The XML document now is:

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <Books>
   3:    <Book publisher="O'Reilly Media, Inc." price="40$">
   4:      <title>Learning WCF: A Hands-on Guide</title>
   5:      <authors>
   6:        <author>Michele Bustamante</author>
   7:      </authors>
   8:    </Book>
   9:    <Book publisher="Microsoft Press" price="45$">
  10:      <title>Introducing Microsoft LINQ</title>
  11:      <authors>
  12:        <author>Paolo Pialorsi</author>
  13:        <author>Marco Russo</author>
  14:      </authors>
  15:    </Book>
  16:  </Books>

Updating data

Updating XML data is also very simple; Just pick the element/attribute you wish to update and then set its new value.

   1:  XElement doc = XElement.Load("Books.xml");
   3:  //obtain a single book
   4:  IEnumerable<XElement> singleBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                      where ((string)b.Element(
   7:                                      "title")).Equals("Introducing Microsoft LINQ")
   8:                                      select b);
  10:  //update book, should only be 1
  11:  foreach (XElement xe in singleBook)

12: {

  13:      xe.SetAttributeValue("price", "39$");
  15:      //use the ReplaceContent method to do the replacement for all attribures
  16:      //this will remove all other attributes and save only the price attribute
  17:      xe.ReplaceAttributes(new XAttribute("price", "32$"));
  18:  }
  20:  doc.Save("Books.xml");

Deleting data

We simply have to get the object we want to delete and then delete it using the Remove() method.

   1:  XElement doc = XElement.Load("Books.xml");
   3:  //obtain the first Book
   4:  IEnumerable<XElement> firstBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                        select b).Take(1);
   8:  //delete book price
   9:  foreach (XElement xe in firstBook)
  10:  {
  11:      xe.Attribute("price").Remove();
  12:  }
  14:  doc.Save("Books.xml");

Other way: we pass a lambda expression in as an argument to the Where extension method.

As you can see, Xlinq is really simple and great way to work with XML.


Query XML using XLINQ

LINQ to XML is a built-in LINQ data provider that is implemented within the System.Xml.Linq namespace in .NET 3.5.
It enables us do the following to XML data:

  • Read.
  • Construct.
  • Write.

We can perform LINQ queries over XML from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content.
LINQ to XML provides much richer (and easier) querying and data shaping support than the low-level XmlReader/XmlWriter API in .NET 2 and also much more efficient with usage of much less memory than the DOM API that XmlDocument provides. That’s because it does not require you to always have a document object to be able to work with XML. Therefore, you can work directly with nodes and modify them as content of the document without having to start from a root XmlDocument object. This is a very powerful and flexible feature that you can use to compose larger trees and XML documents from tree fragments. Now that you have an overview of the XLinq’s capabilities, the next few sections will examine the reading and writing features of XLinq before discussing the query capabilities.

01 (Figure and classes explanations are taken from XLINQ overview.doc)

Of the classes shown in this figure, the XNode and XContainer classes are abstract. The XNode class is the base for element nodes, and provides a Parent method and methods such as AddBeforeThis, AddAfterThis, and Remove for updates in the imperative style. For IO, it provides methods for reading (ReadFrom) and writing (WriteTo).
Although the XElement class is bottom-most in the class hierarchy, it is the fundamental class. As the name suggests, it represents an XML element and allows you to perform the following operations:

  • Create elements with a specified element name
  • Change the element’s contents
  • Add, change, or delete child elements
  • Add attributes to the element
  • Save the element as an XML fragment
  • Extract the contents in text form

This post will introduce hoe to query xml and it is the first of series of posts regards to XLINQ.

Lets get a sense of how LINQ to XML works!

Query xml from URL

   1:  public static void GetRssFeedFromURL()
   2:  {
   3:      string url = "";
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(url);
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}",feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}",feed.Link));
  18:          }
  19:      }
  20:  }

XLinq is an XML query language that inherits from the LINQ query foundation. You can use it to query XLinq objects such as XElement, XDocument, etc using LINQ query facilities.

We start by loading the XML into memory using the Load() method of the XElement class. (Line 6).

After loading the XML , the next step is to retrieve all items (Line 11) and now you can query and iterate the results as described in my previous posts.(Var keyword, Getting started with Linq).

Very simple! This example load an XML from URL. What if you want to query XML from the file system? Nothing changed beside the uri parameter to load into the XElement. (Line 6)

   1:  public static void GetRssFeedFromFile()
   2:  {
   3:      string path = @"C:WorkProjectsSamplesVS2008SamplesLinqToXMLMaor Davids Blog.xml";
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(path);
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}", feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}", feed.Link));
  18:          }
  19:      }
  20:  }


As you can see, all the code snippets presented above are fairly simple. Once the XML loaded into the LINQ to XML API, you can write queries over that tree. The query syntax is easier than XPath or XQuery.


%d bloggers like this: