0

I have created a method that inspects an object and returns a [requested] set of properties.

public static List<object> Inspect<T>(T obj, params Func<T, object>[] funcs)
{
   List<object> results = new List<object>(funcs.Length);

   foreach (var func in funcs)
   {
      results.Add(func(obj));
   }

   return results;
}

It is then invoked, for example on a List, like so:

List<string> peopleData = new List<string>(10) { "name", "age", "address" };
List<object> properties = Inspect(peopleData, p => p.Count, p => p.Capacity);

// The results would be
// properties[0] = 3
// properties[1] = 10

I would like to adapt the Inspect method to instead return a Dictionary<string, object>, where the keys of the dictionary would be the property names. The adapted method would then be invoked like this:

List<string> peopleData = new List<string>(10) { "name", "age", "address" };
Dictionary<string, object> properties = Inspect(peopleData, p => p.Count, p => p.Capacity);

// The results would be
// properties["Count"] = 3
// properties["Capacity"] = 10

Is this possible? If so, and if the solution is reflection-based (as I assume it'd have to be), would there be a big performance hit?

Liath
  • 9,913
  • 9
  • 51
  • 81
psand2286
  • 55
  • 1
  • 5

1 Answers1

1

You'd have to use the classic "interrogation" approach for Func<..> - Retrieving Property name from lambda expression

public static IDictionary<string, object> Inspect<T>(T obj, 
     params Expression<Func<T, object>>[] funcs)
{
   Dictionary<string, object> results = new Dictionary<string, object>();

   foreach (var func in funcs)
   {
      var propInfo = GetPropertyInfo(obj, func)
      results[propInfo.Name] = func.Compile()(obj));
   }

   return results;
}

Ps, as Servy pointed out, you'd also need to make the params use Expression.

Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78
  • The OP doesn't have `Expression` objects. – Servy Jan 12 '15 at 15:36
  • Thanls @chris-eelmaa I was reading through the link you posted, is there any reason why this answer isn't as good? [link](http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression/2916344#2916344) – psand2286 Jan 12 '15 at 16:27
  • @psand2286: no particular reason. I chose the answer one because A) it was the first one, B) it had the same signature, as your `Inspect` function(kind of). – Erti-Chris Eelmaa Jan 12 '15 at 18:39