tags:

views:

51

answers:

2

I need to group data held in a list but can’t hardcode the groupBy clause as it mut be definable by the user.

The example shown below works fine with the hardcoded “r.DeviceID” in the GroupBy statement. What I would like to do is to change this so that an end-user can select the field the expression will be applied to. At the moment the user can select “DeviceId” from a dropdown list. Is it possible to amend the code so that the text “DeviceId” from the list can be used in the example shown below (EG to replace the r.DeviceID bit). This is just a cut down example but the “real” version has many fields, any of which the user may want to group on. Please not that “TEST01-.” Will also be replaced with a user defined regular expression.

List<ThirdPartyExportTransaction> transactions = new List<ThirdPartyExportTransaction>();
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 1 });
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 2 });
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 3 });
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 4 });
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-1", Unit = 5 });
transactions.Add(new ThirdPartyExportTransaction { DeviceId = "TEST01-2", Unit = 6 });


var s= transactions.GroupBy(r => extractText(r.DeviceId, "TEST01-.")); // Need to change this

// At this point s now holds the grouped list

private static string extractText(string fieldText, string regExp)
{
   Match m = Regex.Match(fieldText, regExp);

   return m.Success ? m.Value : "";
} 
+1  A: 

Reflection?

r => extractText(r.GetType().GetProperty("DeviceId").GetValue(r, null), "TEST01-.")
Jerome
Yikes. Performance hog.
Joel Etherton
Well that's the shorthand. You could cache the PropertyInfo object:PropertyInfo prop = typeof(ThirdPartyExportTransaction).GetProperty("DeviceId");
Jerome