2011-12-09 43 views
0

我想將對象集合綁定到Telerik TreeView控件。我的對象結構可能看起來像這樣:基於屬性值的綁定對象集合

Item 1.1 
    - Item 1.1.1 
     - Item 1.2.1 
     - Item 1.2.2 
    - Item 1.1.2 
... 
Item n.1 
    - Item n.1.1 
     - Item n.2.1 
     - Item n.3.1 

所有這些對象都有一個共同的布爾屬性,即isBindable。我想將這個集合綁定到我的TreeView控件,但是隻有當它的屬性isBindable = true時,控件才應該綁定對象。

我不想遍歷整個集合,並在向控件執行ItemSource之前基於isBindable逐個刪除。

有什麼更好的想法我可以用LINQ來實現嗎?

感謝, 巴斯卡爾

+0

爲什麼樹視圖YourCollection.Select(項目=> item.IsBindable)不綁定 – Maheep

回答

0

你可以嘗試實現這一目標使用遞歸。儘管你需要一個單獨的foreach循環。請參閱下面的方法。只需將你的集合傳遞給這個方法,看看它是否被過濾。

private List<Item> Filter(List<Item> itemList) 
     { 

      List<Item> filteredItems = (from c in itemList 
             where c.IsBindable == true 
             select c).ToList(); 
      foreach (Item item in filteredItems) 
      { 
       if (item.Item != null) 
        item.Item = Filter(item.Item); 
      } 

      return filteredItems; 
     } 

class Item 
    { 
     public List<Item> Item { get; set; } 
     public bool IsBindable { get; set; } 

     public Item() 
     { 
      IsBindable = false; 
     } 

    } 
+0

謝謝,這是更多我正在尋找(即使它使用foreach) – Bhaskar

0

可以使用Where篩選項目:

collection.Where(x => x.isBindable); 
+0

我可以將其應用於Tree-like對象集合,就像我在文章中提到的一樣。我可以做一個簡單的對象集合,即List ,但我的obj結構就像一棵樹,即主集合中的每個對象都有一個列表,每個對象2有一個列表,即樹狀結構 – Bhaskar

+0

@Bhaskar:對不起,我不知道Telerik的控制。但我想它應該是這樣的:'treeView.ItemSource = collection.Where(x => x.isBindable);'。你現在如何綁定你的收藏? – Otiel

+0

我簡單地以同樣的方式綁定集合,即treeView.ItemSource = collection。但我的問題是,使用collection.Where(x => x.isBindable)只會過濾頂層對象,那麼它的子對象集合呢,我可以有n層深度的對象集合。 – Bhaskar

0

你可以做一棵樹成線性序列,並檢查您的病情是這樣

collection.SelectMany(item=> item.SubItems).Where(subitem)