List of C# Expandos

(not to be confused with commandos…)

A growing number of “thin” View-Model classes with the only purpose of being able to strongly type the intellisense in my C# MVC views have started to clutter my solution .

Here is an example of where I would typically create a new View-Model class in which to carry the query results back to the page:

var aa = 
  (from rr in db.RiskRatings
   orderby rr.RiskRatingID descending
   select new
   {
     rr.RiskRatingID,
     rr.RiskRatingName,
     SubmissionCounts = db.Submissions.Count(x => x.RiskRatingID == rr.RiskRatingID),
     SubmissionCountsPercentage = ((float)(db.Submissions.Count(x => x.RiskRatingID == rr.RiskRatingID) * 100)) / ((float)db.Submissions.Count())
   });

Brook Patten (brookp.me) has provided an excellent answer to the following question posed on Stackoverflow: “razor view with anonymous type model class. It is possible?

An answer which I thought looked exactly the thing I needed to help me in my dilemma of ever growing View-Model classes.

However, being slightly new to the “Expando” class and loosely typing, I just couldn’t get his extension class to work with the result set from my query above.

Spoiler: that’s because his Expando extension method was written for a single result, ie. FirstOrDefault()

I have now written a new extension that can convert an IEnumerable<object> result set into an IList<Expando>

public static IList ToExpandoList(this object anonymousObject)

Which I call now call here:

var aa = 
  (from rr in db.RiskRatings
   orderby rr.RiskRatingID descending
   select new
   {
     rr.RiskRatingID,
     rr.RiskRatingName,
     SubmissionCounts = db.Submissions.Count(x => x.RiskRatingID == rr.RiskRatingID),
     SubmissionCountsPercentage = ((float)(db.Submissions.Count(x => x.RiskRatingID == rr.RiskRatingID) * 100)) / ((float)db.Submissions.Count())
   }).ToList().ToExpandoList();

The ExpandObject Extension which handles an IEnumerable<object> is openly located here: https://github.com/FrankRay78/ExpandoObject-Extensions/blob/master/Extensions.cs

Thanks Brook for leading the way. And to everyone else, I hope my own extension helps you too.


Frank Ray

Ask any project manager about the key to their success, and they will say that delivering a project is often more like a "dark art" or by chance, than a predictable science.

They may also say that a project going 'off the rails' was one of the most stressful things they have professionally experienced. And unfortunately, it’s all too common.

Risk assessent tool for IT and software development projects. Try it now for free

Leave a Reply