List of Anonymous Types in .Net

1 minute read

While working on an application that uses the great EPPlus  library to export data into an Excel 2007/2010 worksheet I came across an interesting problem. I was using an existing function that return a list of patient gift objects (List), but every PatientGift object in this list has properties that are showing up as blank when the data is exported to an excel file.  I looked around for a solution on how to remove these properties thru reflection and found out it could not be done (unless you used an ExpandoObject which I did not want to use).

I knew that there was a way to use Anonymous Types to construct an object with the desired data. And after a little bit of playing around, I wrote the following code which worked flawlessly:

// the format of Property_Name. This is being done because EEPlus will see the
// underscore character and replace it with a space!
var gifts = giftCollection.Select(i => 
                              new { Date_Created = i.DateCreated.ToString("MMMM dd, yyyy"),
                                    Patient_Name = i.PatientName,
                                    Gift_Name = i.GiftName,
                                    Gift_Value = i.GiftValue.ToString("c"),
                                    Tracking_Number = i.ItemNumber});

And with this simple piece of code I was able to generate my data without any issues (see screenshot below) I will update some of the other parts of the code to use this format to remove some duplicate code in the application!

Leave a comment