2010-08-27 131 views
1

我需要将数据保存在列表中,但不能硬编码groupBy子句,因为它可以由用户定义。Linq 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 : ""; 
} 

回答

1

反射?

r => extractText(r.GetType().GetProperty("DeviceId").GetValue(r, null), "TEST01-.") 
+0

让人惊讶。表演猪。 – 2010-08-27 15:30:23

+0

那就是速记。您可以缓存PropertyInfo对象: PropertyInfo prop = typeof(ThirdPartyExportTransaction).GetProperty(“DeviceId”); – Jerome 2010-08-27 15:32:34