自动更新 C# 中的集合集合

  • 本文关键字:集合 更新 c# collections
  • 更新时间 :
  • 英文 :


我有几个类表现出继承结构:

public class BaseClass
{
Guid ID {get;set;}
}
public class LeafType : BaseClass{ /* omitted */}
public class OtherLeafType : BaseClass{ /* omitted */}    
public class Node : BaseClass
{
public List<LeafType> FirstLeaves {get;set;}
public List<OtherLeafType > SecondLeaves {get;set;}
public ???? AllLeaves {get;} //Returns all items in both FirstLeaves and SecondLeaves
}

在上面的示例中,Node有两个集合,其元素派生自BaseClass。.Net 是否有可以组合这两个集合并在FirstLeavesSecondLeaves更改时自动更新的集合?我找到了System.Windows.Data.CompositeCollection类,但它在PresentationFramework中,对我来说,这表明它是用于UI目的的。我的类Node生活在与 UI 无关的程序集中,因此CompositeCollection看起来不适合。有没有其他类可以达到类似的目的?

更新1:查看到目前为止的答案,似乎我的问题没有明确表述:CompositeCollection允许将多个集合和项目显示为单个列表,但我想知道 .Net 框架是否提供了具有与 GUI 无关的类似功能的类型。如果没有,那么我将推出自己的解决方案,这看起来非常像@Erik Madsen 的答案

我建议使用迭代器。 它不是一个集合,但可以通过 Linq 的 ToList() 扩展方法转换为集合。

迭代器提供集合内容的实时视图。 您需要测试在循环访问 IEnumerable 时基础集合发生突变时会发生什么情况。 但通常这被认为是不好的做法。

public IEnumerable<BaseClass> AllLeaves
{
get
{
foreach (LeafType firstLeaf in FirstLeaves)
{
yield return firstLeaf;
}    
foreach (OtherLeafType secondLeaf in SecondLeaves)
{
yield return secondLeaf;
}
}
}

public List<BaseClass> AllLeavesList()
{
return AllLeaves.ToList();
}

我相信将一个列表连接到另一个列表可能不适用于您的情况,因为它们被声明为不同的类(即使它们继承了Base类)。我会返回一个新组合的列表。

public List<BaseClass> AllLeaves
{
get
{
List<BaseClass> l = new List<BaseClass>();
l.AddRange(FirstLeaves);
l.AddRange(SecondLeaves);
return l;
}
}

最新更新