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 开发者_JAVA百科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 : "";
}
Reflection?
r => extractText(r.GetType().GetProperty("DeviceId").GetValue(r, null), "TEST01-.")
You can compose a lambda expression programmatically:
http://blogs.msdn.com/b/haniatassi/archive/2008/10/28/generating-the-lambda-expression-dynamically.aspx
http://msdn.microsoft.com/en-us/library/bb882637.aspx
精彩评论