2017-01-20 141 views
0

我有一個WPF應用程序,我想填充一個treeview。在這種情況發生之前,我希望用戶能夠從下拉列表中選擇集合中可用的任何字段/屬性,然後使用數據填充樹並進行適當分組。Linq to Collection - Dynamic Where子句

例子中的物體

public class class_01{ 
    public string Property_A {get; set;} 
    public string Property_B {get; set;} 
    public string Property_C {get; set;} 
} 

的例子合集

List<class_01> list_01 = new List<class_01>(); 

再次下拉將用什麼都屬性都可以從列表中的約束。這樣如果列表在哪裏改變應用程序將不需要修改。這是我需要的答案的重要要求。

可以說用戶選擇「Property_A」。

我想要一個像這樣的linq查詢方法。

LINQ查詢

public groupingModel getGrouping(string groupBy) // groupby equals property A in this example 
    { 

     List<class_01> list = getList(); //Returns the list of data of type class_01 

     var q = from x in w where ????? == groupBy select x; // I dont want to specify a specific property but rather have one applied dynamically 

     return q; 
    } 

我有一個查詢將被解析成自定義對象。這看起來類似於以下內容。

自定義對象

public class class_02{ 
    public string header {get; set;} // will be set to the discrete values of the selected groupby property 
    public List<class_01> prop_a {get; set;} 
} 

這將被綁定到樹適當。

有什麼想法?

編輯

此外,我將如何得到用戶選擇屬性的唯一值的列表。

例如

{A = 1,B = 2,C = 3},{A = 2,B = 3,C = 4}

如果用戶決定基上屬性「一個「我們將如何產生[1,2]的集合?

這將需要構造一個where子句。

foreach(value of user selected property){ 
    string whereClause = string.format("{0} = {1}",selected property, value") 
} 

編輯 - 從動態查詢捕捉異常

public List<groupingModel> getGrouping(string groupBy) 
     { 
      List<groupingModel> lgm = new List<groupingModel>(); 

      //Categories.Select(c => c.Id).ToList() 
      var w2 = getWVWellsList(); 
      //var v = w2.Select(groupBy).Distinct().Cast<string>().ToArray(); 
      var v = w2.Select(groupBy).Distinct(); 

      foreach(string val in v) 
      { 

       string whereClause = string.Format("{0} = {1}", groupBy, val); 

       try 
       { 

        IEnumerable<WVWellModel> q2 = w2.Where(whereClause); 
        List<WVWellModel> l = q2.ToList<WVWellModel>(); 

        lgm.Add(new groupingModel { Header = val, Wells = l }); 
       } 
       catch (Exception e) 
       { 
        MessageBox.Show(e.Message, "Query Error", MessageBoxButton.OK, MessageBoxImage.Error); 
        throw new Exception("Generic Exception - Issue With Group By Query", e); 
       } 

      } 

      return lgm; 
     } 

異常 「否屬性或字段 」科羅拉多「 存在於型WVWellModel」

在本例的情況下我可以證實我的where子句是「State = Colorado」。看起來查詢正在應用該值,而不是屬於該類型的屬性狀態。它就好像在查詢被調用時被顛倒過來一樣。

回答

2
+0

阿哈的帖子!這非常方便。你會如何建議我爲動態查詢生成一個可能的值列表?或者有沒有辦法在圖書館處理?我編輯了我的問題以包含該步驟。感謝您輸入@Tito。 – LCaraway

+0

我編輯了我的問題以使用動態Linq查詢。我建立一個字符串where子句,雖然我面臨一些問題。拋出異常,指示正在應用錯誤的字符串屬性。 – LCaraway