Thursday, July 31, 2008

I just had a Pwop moment (the sound of a forehead slap) with LINQ:

I needed to retrieve a distinct list of years contained in a collection of objects. The data was in the form of an generic List<T>, already loaded into memory. So without thinking too much about it, I sat down and wrote a quick LINQ expression that included the Distinct() operator and since the years were actually properties on the objects, I wrote my own implementation of IEqualityComparer.

It had some problems because the resulting data was not really all that distinct, and then it happened: PWOP!

I don't need to implement an interface. I can simply use the default equality comparer for a List<int> like so.

LINQ Distinct() Operator

Gah!

Thursday, July 31, 2008 9:52:54 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 

Behind the scenes, I see a lot of companies run on Excel and duct tape. So it's common for clients to hand me a slab of data organized into neat little rows and columns. Excel is just a handy way to throw some data over the wall and get things done. This might be a list of dealers, a collection of user profiles, product information, or anything that just needs to get somewhere else.

Depending on the scenario, I'll might massage this data and slide it into a SQL Server database or an XML file. I'm a web developer so I use the ADO.Net stack on a regular basis. If I were a Windows client developer, I might prefer to solve this problem with the Excel object model, but that really looks like more code to me, so here's how I like to roll:

The following code block accepts an Excel file path and returns an ordinary DataTable object, which can be manipulated easily by the code that calls this method. The first row of the Excel document becomes the columns in the DataTable object and each row thereafter are DataRow objects.

ImportDataFromExcel
(Click to enlarge)

If you like, take a look at both techniques for working with Excel data and see what one speaks to you. With this block of code, I can happily accept large chunks of data from a client without spending precious time fiddling with administrivia.

Thursday, July 31, 2008 8:00:16 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |