从类实体获取类型T的项目列表

时间:2013-04-06 13:01:03

标签: performance list c#-4.0

我有A级以下结构

 public class A
  {
   public list<B> Items // where B is a class entity
  }

  public class B{
    public List<B> OwnItems;
    public List<C> Items // where C is a class entity
   }

  public class C
  {
   public string name;
   public string Address;
   public int Age;
   public double Salary;
  }

如何使用c#

从实体A获取C类实体列表

2 个答案:

答案 0 :(得分:0)

您可以在 SelectMany 的帮助下使用LINQ:

A a = new A();
// Populate a's `Items` property...
....

var allC = a.Items.SelectMany(b => b.Items.Select( c => c)).ToList();

答案 1 :(得分:0)

var a = new A();
var bList = a.Items;
var cList = new List<C>();
while(bList != null && bList.Count > 0)
{
    foreach(var b in bList)
        cList.AddRange(b.Items);

    bList = bList.SelectMany(b => b.OwnItems)
                 .Where(b => !bList.Contains(b))
                 .Distinct().ToList();
} 

对我来说不是最好的,但会起作用