stupid hack of the day: the useless enumerable

There’s a few times I want to keep something (like setting e.Result in a LinqDataSource’s Selecting event) in the form of “from row in foo select new { row.X, row.Y }” and the like.  However, sometimes I don’t actually have a queryable/enumerable around (testing or whatever), I just have an object.

I could certainly switch to a different format and just create the one new (anon or otherwise) instance, but I like the consistency in the query comprehension syntax.

So, I added quite the stupid extension method just so I can make anything into an enumerable that returns just itself.

Hopefully it’ll serve as at least a negative example for someone out there 🙂


public static IEnumerable<T> AsEnumerableOfOne<T>(this T self)
    yield return self;

For instance, if I have a method that does a .Single() call into a database already, like db.Users.Single(row => row.ID == userID);

Then I have var user = GetThatUser();

If I want to return a projection, I could certainly just directly e.Result = new { user.Foo, user.Bar }; but to keep it in the syntax, I can now do:

from row in user.AsEnumerableOfOne() select new { row.Foo, row.Bar };

It also helps in cases where you need the result to be enumerable anyway (like the data for a gridview).

I’m also apparently weird for picking ‘row’ as my query comprehension variable name of choice.  I used to do like others using the first letter of the thing you were selecting, like “from u in db.Users” or “from f in db.Files” but it just felt annoying to have to pick different letters and they offered nothing to me, so I’m now consistent in using ‘row’ and it helps remind me in those queries what I’m doing at runtime (rows from a backend data store, as storage-agnostic as the current chants are).