Keep the LINQ short

LINQ Unleashed for C# by Paul Kimmel
 
This was a fairly interesting read which went through the various changes to C# as the language moved between versions 2 and 3, covering in some detail the LINQ extensions. There were chapters in the various LINQ combinators and the syntax extensions in the form of the select statement which allows easy use of them.
There was fairly detailed coverage of LINQ to SQL and examples of its use in a couple of example applications. The text also covered an example LINQ to Active Directory provider as a way to show what you have to do to implement a LINQ provider.
 
The book was interesting, but some of the examples were too long, in that the code extended sometimes for 8 to 10 pages.
 
Unfortunately, a couple of things in the book were clearly wrong.  For example, there’s an example of shuffling cards which uses the rather consise syntax
 
            const int numberOfCards = 52;
            int[] cards = new int[numberOfCards];
            var shuffler = cards.Select((num, index) =>
                            new { Key = index, Random = random.Next() });
            var result = Array.ConvertAll(shuffler.OrderBy(s => s.Random).ToArray(), s => s.Key);
 
The trouble is that the distribution of possible hands using this scheme isn’t uniform. For example, with three cards, and using random numbers in the range 0-19, we get the distribution
 
   [1,2,0]  1330
   [0,2,1]  1330
   [2,0,1]  1330
   [2,1,0]  1140
   [0,1,2]  1540
   [1,0,2]  1330
 
In another chapter, the sieve schemes for generating prime numbers look very odd and not at all like the usual Sieve of Erastothenes.
There’s also some code where we use the type of a default value by a runtime call of GetType() instead of using the generic type of the method.
 
ie instead of
 
        static T ConvertTo<T>(object o, T defaultValue)
        {
            return (T) Convert.ChangeType(o, defaultValue.GetType());
        }
 
I don’t see why we don’t rather use
 
        static T ConvertTo2<T>(object o, T defaultValue)
        {
            return (T)Convert.ChangeType(o, typeof(T));
        }
In summary, the book was a good way of seeing lots of examples of LINQ syntax and its uses, but I think I could have done just as well with smaller examples.
 
Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s