2013-10-23 33 views
3

我想填充一個下拉與特定的對象,我已經做了精細的公共屬性。但是現在,當用戶從下拉列表中選擇值時,我希望它按該列對數據庫表結果進行分組。我曾嘗試使用LINQ,但我只能弄清楚如何通過實例變量屬性顯式分組,而不是通過反射屬性。這是我的方法 - 傳入的參數是屬性的字符串名稱。例如,如果用戶想要通過Customer.Country進行分組,那麼它將是「國家」,如果用戶想要通過Customer.State進行分組,則它將是「狀態」。但此刻我已經硬編碼到由「國家」集團,因爲我無法弄清楚如何使用我的LINQ查詢LINQ組通過查詢使用反射屬性名

private void DisplayReportAction(string category) 
{ 
    if (!string.IsNullOrEmpty(category)) 
    { 
     SelectedCategory = category; 
     _summaries.Clear(); 

     foreach (var custGroup in _customerInterface.CustomerInterface.GetAllCustomers().GroupBy(c => c.State) 
      .Select(group => new 
           { 
            Category = group.Key, 
            Count = group.Count() 
           }) 
           .OrderBy(x => x.Category)) 
     { 
      _summaries.Add(new CustomerReportSummaryViewModel(custGroup.Category, custGroup.Count)); 
     } 

     ReportVisibility = Visibility.Visible; 
    } 
} 

回答

13

你可以,如果你正在使用LINQ到對象使用反射傳遞的字符串值,比如,你可以這樣做:

_customerInterface.CustomerInterface.GetAllCustomers() 
    .GroupBy(c => c.GetType().GetProperty(category).GetValue(c, null)) 

如果您正在使用LINQ to SQL的則另一種是使用動態查詢,檢查此鏈接

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

+0

這很好用一個修改。上面的代碼將返回屬性對象,如果您通過屬性名稱進行分組,則可以使用屬性名稱的標籤在單個存儲桶中返回所有內容。爲了得到這個工作,你需要通過條款,使羣 「.GroupBy(C => c.GetType()的getProperty(類別).GetValue(C,NULL))」 – NZJames

+0

@ user1122909,我明白了,你是對的,更新了答案,謝謝! –

3

,您可以動態地構建表達:

Expression<Func<Customer,T>> buildExpression<T>(string category) 
    { 
     //First build parameter of lambda ('c =>' part of expression) 
     ParameterExpression param = Expression.Parameter(typeof(Customer), "c"); 
     //Then body of expression : ' => c.category' 
     Expression<Func<Customer, T>> exp = Expression.Lambda<Func<Customer, T>>(Expression.Property(param, category), param); 
     return exp; 
    } 

最後,調用

_customerInterface.CustomerInterface.GetAllCustomers() 
    .GroupBy(buildExpression(category)) 

編輯: 嗯,對不起,你還必須知道的屬性的類型給T類參數buildExpression功能

有辦法做到這一點,例如使用GetProperty(category).PropertyType,然後在GetType().GetMethod("buildExpression<>")上撥打MakeGenericMethod,但這需要多一點工作。 無論如何,你必須找到一種方法來構建這種類型的CustomerReportSummaryViewModel

我不知道你的使用情況,但你也許所有類別的性質是相同類型的,所以你可以硬編碼呢?

如果你有興趣,並不能找到一個適當的方式做到這一點,讓我知道我會嘗試寫一個妥善的解決辦法。