Archive for the ‘LINQ’ Category

Autoprojecting LINQ queries

Something I’ve been looking at adding to AutoMapper was the idea of doing automatic query projection in the Select query projection in LINQ statements.  One downside of AutoMapper is that projection from domain objects still forces the entire do…

VS 2010 SP1 and SQL CE

Last month we released the Beta of VS 2010 Service Pack 1 (SP1).  You can learn more about the VS 2010 SP1 Beta from Jason Zander’s two blog posts about it, and from Scott Hanselman’s blog post that covers some of the new capabilities enabled …

Class-Level Model Validation with EF Code First and ASP.NET MVC 3

Earlier this week the data team released the CTP5 build of the new Entity Framework Code-First library.  In my blog post a few days ago I talked about a few of the improvements introduced with the new CTP5 build.  Automatic support for enforc…

The Weekly Source Code 56 – Visual Studio 2010 and .NET Framework 4 Training Kit – Code Contracts, Parallel Framework and COM Interop

Do you like a big pile of source code? Well, there is an imperial buttload of source in the Visual Studio 2010 and .NET Framework 4 Training Kit . It's actually a 178 meg download, which is insane. Perhaps start your download now and get it in the morning when you get up. It's extremely well put together and I say Kudos to the folks that did it. They are better people than I. I like to explore it while watching TV myself and found myself looking through tonight. I checked my blog and while I thought I'd shared this with you before, Dear Reader, I hadn't. My bad, because it's pure gold . With C# and VB, natch. Here's an outline of what's inside. I've heard of folks setting up lunch-time study groups and going through…(read more)

The Weekly Source Code 51 – Asynchronous Database Access and LINQ to SQL Fun

You can learn a lot by reading other people's source code. That's the idea behind this series, " The Weekly Source Code ." You can certainly become a better programmer by writing code but I think good writers become better by reading as much as they can. I was poking around in the WebFormsMVP project's code and noticed an interesting pattern . You've seen code to get data from a database and retrieve it as an object, like this: public Widget Find(int id) { Widget widget = null; widget = (from w in _db.Widgets where w.Id == id select w).SingleOrDefault(); return widget; } This code is synchronous, meaning basically that it'll happen on the same thread and we'll wait around until it's finished. Now, here's…(read more)

Building custom LINQ expressions made easy with DynamicQueryable.

A colleague of mine recently called me out on the fact that I haven’t blogged in … oh about a year and a half. Well it’s 2010 now and resolution season is in full swing so here’s my attempt at getting back on the ball (no promises th…

Building custom LINQ expressions made easy with DynamicQueryable.

A colleague of mine recently called me out on the fact that I haven’t blogged in … oh about a year and a half. Well it’s 2010 now and resolution season is in full swing so here’s my attempt at getting back on the ball (no promises th…

LINQ query operators and null lists

One of my pet peeves with the LINQ extension methods is their inability to handle null source lists.  For example, this will throw an ArgumentNullException:

[Test]
public void Should_handle_nulls()
{
    List<int> ints = null;

    ints.Any(num => num < 0).ShouldBeFalse();
}

Now I know what you’re saying – why not check for null, or not allow the list to be null in the first place?  After all, the Framework Design Guidelines book recommends that methods and properties that return collection types never be null.  This is so you can merely check for empty collections, and not force users to have null checks everywhere.  That’s all fine and dandy…until you’re forced to interact with systems that don’t play nice.  Especially around serialization libraries, we find places where they don’t abide by this suggestion.

Instead, we have to add a rather annoying, but necessary extension method:

public static IEnumerable<TSource> NullToEmpty<TSource>(
    this IEnumerable<TSource> source)
{
    if (source == null)
        return Enumerable.Empty<TSource>();

    return source;
}

And now my test will pass, as long as I make sure and convert these values properly:

[Test]
public void Should_handle_nulls()
{
    List<int> ints = null;

    ints.NullToEmpty().Any(num => num < 0).ShouldBeFalse();
}

So yes, it’s annoying, and I’d rather the LINQ operators just ignore null collections, or replace them with Enumerable.Empty().  Until then, we just have to use this annoying extension method.

Kick It on DotNetKicks.com

More missing LINQ operators

Continuing an old post on missing LINQ operators, the wonders of extension methods allow us as developers to fill potential holes in LINQ operators.  Whether it’s a Zip method (now included in .NET 4.0), or better methods for IComparer-based operators, I find myself adding more and more helpful LINQ operators, I wish were already in the framework.

Alternate

Do you ever want to weave two collections together, like shuffling a deck of cards?  Well I know I do!  Suppose we have this collection:

[1, 3, 5]

And this collection:

[2, 4, 6]

I’d like to create new collection that is the alternating items from the first and second list:

[1, 2, 3, 4, 5, 6]

Here’s the code to do it:

public static IEnumerable<TSource> Alternate<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
{
    using (IEnumerator<TSource> e1 = first.GetEnumerator())
    using (IEnumerator<TSource> e2 = second.GetEnumerator())
        while (e1.MoveNext() && e2.MoveNext())
        {
            yield return e1.Current;
            yield return e2.Current;
        }
}

Very simple, I iterate both enumerables at the same time, yielding the first, then second collection’s current item.  So how is this useful?  How about this action:

[Test]
public void Word_play()
{
    var source = new[] {"The", "quick", "brown", "fox"};

    var result = source.Alternate(Spaces()).Aggregate(string.Empty, (a, b) => a + b);

    result.ShouldEqual("The quick brown fox ");
}

private IEnumerable<string> Spaces()
{
    while (true)
        yield return " ";
}

I cheated a little bit with an infinite sequence (the Spaces() method), but I found this method useful when I had to split, then reconstruct new sequences of strings.

Append

I really hate this syntax:

[Test]
public void Bad_concat_method()
{
    var ints = new[] {1, 2, 3};

    var oneToFour = ints.Concat(Enumerable.Repeat(4, 1));

    CollectionAssert.AreEqual(new[] { 1, 2, 3, 4 }, oneToFour.ToArray());
}

I want to just stick an item on the end of an existing collection, but I have to use this arcane Enumerable.Repeat method to do so.  Instead, let’s create an operator that lets us tack an item on to the end of a collection:

public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element)
{
    using (IEnumerator<TSource> e1 = source.GetEnumerator())
        while (e1.MoveNext())
            yield return e1.Current;

    yield return element;
}

Now our code becomes much easier to understand:

[Test]
public void Easier_concat_with_append()
{
    var ints = new[] {1, 2, 3};

    var oneToFour = ints.Append(4);

    CollectionAssert.AreEqual(new[] { 1, 2, 3, 4 }, oneToFour.ToArray());
}

Prepend

Append wouldn’t be complete without the converse, Prepend, now would it?

public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element)
{
    yield return element;

    using (IEnumerator<TSource> e1 = source.GetEnumerator())
        while (e1.MoveNext())
            yield return e1.Current;
}

Now putting something on the beginning of a list is easier as well:

[Test]
public void Easier_concat_with_prepend()
{
    var ints = new[] {1, 2, 3};

    var zeroToThree = ints.Prepend(0);

    CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, zeroToThree.ToArray());
}

Much more readable.  I have a few more around replacing the IEqualityComparer<T> overloads, but those are a little bit more esoteric in their examples of crazy set-based logic.  What’s really cool about all these methods is they still allow all sorts of fun chaining, allowing me to create very terse chains of operations on lists, with what would have taken a bazillion cryptic for..each loops.  Cool stuff!

Kick It on DotNetKicks.com