2010-08-27 106 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