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

Frank Ray & Associates is a software engineering consultancy that builds high quality software for businesses.

We develop new applications, automate manual processes, integrate vendor packages, replace Excel workarounds, fix unreliable applications, retire end of life software and remove dependence on poor value suppliers.

Get in touch if you need our help