2011-12-09 39 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)