【发布时间】:2010-08-27 15:24:51
【问题描述】:
我需要对列表中保存的数据进行分组,但不能对 groupBy 子句进行硬编码,因为它必须由用户定义。
下面显示的示例在 GroupBy 语句中使用硬编码的“r.DeviceID”可以正常工作。我想做的是改变它,以便最终用户可以选择将应用表达式的字段。目前,用户可以从下拉列表中选择“DeviceId”。是否可以修改代码,以便可以在下面显示的示例中使用列表中的文本“DeviceId”(EG 替换 r.DeviceID 位)。这只是一个精简的示例,但“真实”版本有许多字段,用户可能希望对其中的任何一个进行分组。请不要说“TEST01-”。也将替换为用户定义的正则表达式。
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 : "";
}
【问题讨论】: