Saturday, April 05, 2008

Today I needed to add an special field to my LINQ query. A kind of Row Number column. Actually it was not a row number nor was it a column since LINQ deals with objects, but since it was used for presenting data in a tabular way, I see no other name that fits the description.

So, I needed a data displayed in a following format:

Lp. Name
1 Murray N. Rothbard
2 Hans-Hermann Hoppe
3 Ludwig von Mises

First column had to be generated somehow. Using LINQ. I made few quick searches on google, but whith no success, so I came out with my own solution:

int i = 1;
return from author in DataContext.Authors
       select new Author() { Lp = i++, Name = author.Name };

So very simple. Isn't it?

Friday, April 04, 2008 11:15:34 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 
 Wednesday, April 02, 2008

Today while using Reflector I've noticed one funny thing. It came out, that we are able to see where Microsoft keeps their PublicKey files and what are their names :-)

Few samples:

mscorlib f:\RedBits\Tools\devdiv\EcmaPublicKey.snk
System.Data.Linq f:\dd\tools\devdiv\EcmaPublicKey.snk
System.Web f:\RedBits\Tools\devdiv\FinalPublicKey.snk
Microsoft.VisualBasic f:\\RedBits\\Tools\\devdiv\\FinalPublicKey.snk

Nothing special, but... Keep this in mind when doing RTM so you don't something that shouldn't be distributed, like: CustomersIHate\Customer1\Key.snk

Wednesday, April 02, 2008 5:55:40 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Tuesday, April 01, 2008

One thing that I like about SQL is the IN operator which checks if an argument is equal to any of the listed elements. C#/.NET doesn't offer this kind of operator which forces us to use code similar to the one below:

int i = 5;
if (i == 5 || i == 4 || i == 3)
{
    return;
}

Wouldn't it be better if we could just write like this:

if (i.In(5, 4, 3))
{
    return;
}

What we need is a simple Extension Method:

public static bool In<T>(this T source, params T[] values)
{
    return values.Any(v => v.Equals(source));
}

Few things to notice. First I'm using generic type parameter T to avoid boxing for Value Types. Second, it would probably be a wise thing to write few overrides like this:

public static bool In(this IComparable source, params IComparable[] values)
{
    return values.Any(v => v.CompareTo(source) == 0);
}

And another one for generic version. Finally it would be wise to provide an overload that accepts IEqualityComparer, like like LINQ extension methods do.

Whatever you do, you just have to love Extension Methods :-)

Tuesday, April 01, 2008 9:32:49 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |