|
|
-
-
Do you know LINQPad? It's a really simple but great tool for testing LINQ queries. Not only that, but it can be used to test all kinds of C# and VB code snippets.
Another great thing about LINQPad is that it comes with code samples. Until now the integrated code samples came from the C# 3.0 in a Nutshell book. Joe Albahari, author of LINQPad and C# 3.0 in a Nutshell, has opened LINQPad so that code samples from other books can be integrated into LINQPad. Thanks Joe for this opportunity!
We worked with Joe to integrate LINQ in Action's code samples into LINQPad. The result is that in addition to being available as Visual Studio solutions and projects, you can now run our code samples directly from LINQPad. This makes it very easy to explore LINQ's features with instant "code and play".
To install LINQ in Action's code samples in LINQPad, all you have to do is click on the "Download more samples..." link:
You'll see LINQ in Action proposed as one of the LINQPad-enabled books (the only one at the moment, in fact):
Once you've clicked on "Download full code listings into LINQPad", you should see the C# and VB samples grouped by chapter:

Currently, chapters 1 to 8 are available. We'll integrate the remaining code samples soon.
Have fun with LINQ!
|
-
Eric Lippert, whose blog you shouldn't miss, adds his own arguments to the debate about whether using a ForEach extension method instead of foreach is a good idea or a bad one. I don't see a definitive answer to the question. All the arguments given here and elsewhere are good, but in the end, it's up to you to decide what you prefer to do. Read the posts and the comments to make up your own mind.
|
-
-
Today I had the pleasure to receive a copy of LINQ in Action translated in Spanish. This came a bit unexpected, but it's great! LINQ in Action already existed in German (LINQ im Einsatz), and I know that other translations should be published soon. The Chinese version is the next one expected, I believe. The Spanish version of the book is published by Anaya Multimedia. The title of the book is simply... "LINQ"! ¡Espero que disfruten la lectura de este libro!
|
-
-
In LINQ in Action, we discuss about the missing ForEach query operator. This is in Chapter 5 "Beyond basic in-memory queries", more precisely in section 5.2.2. There, we indicate that Eric White suggested this operator in his functional programming tutorial, although I'm not able to find the exact reference at the moment in this tutorial.
Since then, a lot of people have been asking for ForEach. This can be seen on Kirill Osenkov's blog, where you'll find links to discussions about whether ForEach is good or bad. I don't know if we're going to see ForEach appear in .NET. Anyway, it's not very difficult to write your own:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action");
foreach (var item in source) action(item); }
|
-
Yesterday a reader of the LINQ in Action book posted an interesting challenge on the book's forum. It's interesting enough to be reposted it here.
The request was to convert a LINQ query expression (query syntax) to a query operator call chain (method syntax or dot notation). The original query was the following one:
from publisher in SampleData.Publishers join book in SampleData.Books on publisher equals book.Publisher into publisherBooks from book in publisherBooks.DefaultIfEmpty() select new { Publisher = publisher.Name, Book = book == default(Book) ? "(no books)" : book.Title };
This query comes from LINQ in Action. In chapter 4 more precisely, where we cover grouping and joins.
Converting LINQ queries is an interesting exercise because it's not always easy to find the solution but you learn a lot in the process. Often, you'll have to use "tricks". Here the tricks are based on the use of anonymous types. Side note: this is also what you'd use to translate the let keyword.
Here is the solution I gave:
SampleData.Publishers .GroupJoin(SampleData.Books, publisher => publisher, book => book.Publisher, (publisher, publisherBooks) => new { Publisher = publisher, PublisherBooks = publisherBooks }) .SelectMany( group => group.PublisherBooks.DefaultIfEmpty<Book>(), (group, book) => new { Publisher = group.Publisher.Name, Book = (book == null) ? "(no books)" : book.Title });
Not as easy to read as your original query, don't you think? See my previous post about Query syntax vs. Method syntax to decide which syntax is best for you.
"How did he manage to convert the query," you may be wondering... Well, even if I know the tricks, the easiest is to use .NET Reflector to decompile the IL. If you specify ".NET 3.5" for the Optimization option, you'll see the query expression. But if you specify ".NET 2.0", you'll see something that looks close to the above query. You'll have to replace the anonymous methods with lambda expressions and change the name of the anonymous parameters to make the code somewhat more readable, though.
As usual, Reflector is your best friend. It reveals a lot of secrets ;-)
Update: Joe Albahari, of LINQPad fame, suggested other solutions:
1) Calling .ToString() on the query's expression will work just fine if you add AsQueryable() to the first sequence: from publisher in SampleData.Publishers.AsQueryable() join book... 2) If you use LINQPad to run the query, you'll notice it shows lambda translations for all IQueryable-based queries. LINQPad uses its own expression visitor so the result is much more readable than simply calling ToString on the expression.
|
-
-
Yesterday, Fred asked me if I could help him to convert C# code to LINQ. The solution may not obvious to find unless you know LINQ well. I will reproduce here the solution I gave Fred. Whether the LINQ version of the code is easier to read than the original one is arguable. The purpose here is more to show LINQ's Select query operator in action.
Here is the original code:
int CountCorrectChars(string proposedValue, string correctValue) { int correctCount = 0; for (int i = 0; i < proposedValue.Length && i < correctValue.Length; i++) if (proposedValue[i] == correctValue[i]) correctCount++; return correctCount; }
Here is the LINQ version that I suggested:
int CountCorrectChars(string proposedValue, string correctValue) { return correctValue .Select((testChar, index) => new { Character = testChar, Index = index }) .Count(testChar => (testChar.Index < proposedValue.Length) && (testChar.Character == proposedValue[testChar.Index])); }
As you can see, the LINQ version is not so easy to understand and is verbose. Of course, we could use shorter names, but that wouldn't change the complexity of the query. The LINQ version is not as good in terms of performance either... So, should we use LINQ or not? My point here is that LINQ is not a "one size fits all" solution. You should use it wisely and avoid complexifying code by choosing always to use LINQ.
What's interesting in this example, is also simply the use of Select with a two-parameter lambda expression. You may know the version of Select that takes a single-parameter lambda well, but its counterpart is less known (and used).
This is something that we cover in LINQ in Action in section 4.4.2. Here is what we write there, which gives another example of Select in action:
The Select and SelectMany operators can be used to retrieve the index of each element in a sequence. Let’s say we want to display the index of each book in our collection before we sort them in alphabetical order:
index=3 Title=All your base are belong to us index=4 Title=Bonjour mon Amour index=2 Title=C# on Rails index=0 Title=Funny Stories index=1 Title=LINQ rules Here is how to use Select to achieve that:
Listing 4.15 Code-behind for the first ASP.NET page (SelectIndex.csproj)
var books = SampleData.Books .Select((book, index) => new { index, book.Title }) .OrderBy(book => book.Title); ObjectDumper.Write(books); This time we can’t use the query expression syntax because the variant of the Select operator that provides the index has no equivalent in this syntax. Notice that this version of the Select method provides an index variable that we can use in our lambda expression (precision not in the book: its not the name "index" that is important. You can use another name if you want. What makes the difference is that the lambda expression takes two parameters). The compiler automatically determines which version of the Select operator we want to use just by looking at the presence or absence of the index parameter. Notice also that we call Select before OrderBy. This is important to get the indices before the books are sorted, not after.
...One more tool in your toolbox. Now, use it wisely. Update: Mark Sowul suggests a simpler solution:
return correctValue.Where((testChar, index) => index
< proposedValue.Length && testChar ==
proposedValue[index]).Count();
Somehow I missed that Where overload.
|
-
I'll be at TechEd in Barcelona next week. I'll be at the Ask The Experts booths a few hours during the week. Feel free to come and say hello. I'll be available if you want to discuss about LINQ, the LINQ in Action book, WPF and Silverlight, my projects, or .NET in general :-) Please ping me if you'll be there too and would like to meet.
|
-
DevTeach Montréal will take place this year between December 1 and 5. I have the pleasure to take part to this event and speak in no less than five sessions!
Here are my sessions, all in French:
- Tout d'abord une série de quatre sessions que j'ai le plaisir de présenter avec Frédéric Schäfer. Il s'agit d'une reprise enrichie de notre session de l'Université du SI.
Ces sessions vous permettrons de découvrir LINQ, Entity Framework, WPF, Silverlight et WCF en action. Il n'est pas nécessaire d'assister à l'ensemble des quatre sessions. Vous pouvez très bien n'assister qu'à certaines sessions. Nous fournirons un bref récapitulatif des épisodes précédents au début de chaque session.
- Application Order Tracking - 1/4 - Créer un modèle métier testé avec Entity Framework et manipuler des données avec LINQ
- Application Order Tracking - 2/4 - Développer une interface utilisateur riche et testable avec WPF en utilisant des design patterns
- Application Order Tracking - 3/4 - Persister ses objets avec Entity Framework et adapter l'interface utilisateur en conséquence
- Application Order Tracking - 4/4 - Développer une application Silverlight distribuée avec WCF
- Je présente également une session en solo : Nouveautés des langages C# 3.0 et VB 9.0 (LINQ)
Il s'agit d'une reprise de la session d'Introduction à LINQ, C# 3.0 et VB 9.0 que j'ai jouée avec Philippe Mougin durant les Microsoft TechDays France.
Frédéric présente une session en solo : Développement piloté par les tests. Toutes les sessions sont détaillées sur le site de DevTeach.
Rendez-vous donc début décembre pour retrouver avec nous la fraîcheur de Montréal à cette époque et la chaleur de nos amis québécois !
|
-
In July, I was invited by Mario Cardinal and Guy Barrette to register a session for their Visual Studio Talk Show podcast. This session is now online. During one hour, Guy, Mario and I discuss about LINQ in French. You can find the podcast here. I hope that you'll enjoy it and that it'll help you to learn more about LINQ's whats, whys and hows.
I'd like to thank Mario and Guy for giving me this opportunity. It was a very good experience!
|
-
Today, I received a copy of LINQ im Einsatz. This is the German translation of LINQ in Action. It's now available from Amazon.de and from Hanser.
Bonus: The German version is bigger than the English one. It contains chapter 14, which covers LINQ to DataSet and is provided in English only as a PDF download from Manning's website.
Maybe we'll see translations in other languages next. French would be a good idea, for example ;-)
Viel Spaß beim Lesen!
|
-
|
|
|