Posts tagged LINQ

Design Guidelines for LINQ

Have you wondered if and when you should use the new LINQ features in .Net 3.5?

Like, where should I put a new extension method? Should I use Func<T> or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?

Well, Mircea Trofin has just published a new draft of some LINQ design guidelines. You might just find your answers there.

How to Update Data with LINQ-to-SQL

When learning LINQ-to-SQL, it’s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context.

var product = (from p in dataContext.Products
               where p.ProductID == 1
               select p).Single();

product.Name = "Richard's product";

dataContext.SubmitChanges();

It’s nice to see that MSDN documentation actually addresses the obvious arising question:

Q. Can I update table data without first querying the database?

A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:

  • Use ExecuteCommand to send SQL code.
  • Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change.

More >

How to See the SQL Generated by a LINQ to SQL Command

Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.

If this is your code:

using System;
using System.Linq;
using System.Data.Linq;

namespace LINQtoSQLConsole {
  class Program {
    static void Main(string[] args) {

      var db = new NorthwindDataContext();

      // Use the console to see the SQL
      db.Log = Console.Out;

      // A query
      var cust = db.Customers.Single(
                    c => c.CustomerID == "ALFKI");

      // An update
      cust.Region = "Northwest";
      db.SubmitChanges();
    }
  }
}

… then this is what you’ll see:

image

Pretty good, eh?

How to Use Grouping in C# LINQ Syntax

When you started using LINQ, did you think it looked like SQL? I did.

The more I learned LINQ, the more I realized it wasn’t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.

At first glance, the two syntaxes look slightly similar.

SQL:

select ReportsTo, count(LastName) as NameCount
from Employees
group by ReportsTo

LINQ (C#):

from employee in Employees
group employee by employee.ReportsTo

Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.

Let me explain why.

More >

LINQ to DataSets – the Missing Manual

Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to "LINQ to DataSets". I couldn’t find any more information about it though, and so LINQ to DataSets got a small mention in my presentation, but I couldn’t say anything more about it.

This morning I discovered that Fabrice Marguerie and his co-authors have published a bonus 47-page chapter of their book "LINQ in Action", all about this very subject. The chapter is called "Working with LINQ and DataSets", and they have made a PDF version available online for FREE download from the Manning Press website.

You can go get it right now.

Thanks Fabrice, for filling in the missing gap.

I’m going back to update my presentation…

Using LinqPad to Create a Time-Selector Drop-Down List

I am really getting into LINQ now! I think it’s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this:


08:00
08:15
08:30
08:45
09:00

… and so on.

Before LINQ, I would have done this with a for loop, like this:

List<string> times = new List<string>();
for (int hour = 0; hour < 24; hour++)
  for (int minute = 0; minute < 60; minute++)
    if (minute % 15 == 0)
       times.Add(string.Format(
         "{0:00}:{1:00}", hour, minute));

That’s not difficult, although it’s not so easy to understand. I would have to write a small console app or test to make sure I had done it correct though.

I thought this might be a good opportunity to use LinqPad. It’s a great tool. You can use it to test a LINQ statement in a live window, so I thought I’d give it a go.

First I needed a LINQ statement to test.

More >