访问列表构造函数

时间:2019-05-03 14:16:45

标签: c# list constructor

首先,对术语不正确表示歉意。我有一个像这样的构造函数:

public class A
{
  public int B { get; set; }
  public ICollection<C> C { get; set; }     
}

public class C
{
    public int D { get; set; }
}

我正在尝试像这样访问有关D的信息:

List<A> listA = New List<A>;
if (listA != null)
{
      foreach (var temp in listA)
      {
         if (temp.C.D.contains(123)) --> got an error here
         {
         }
       }
  }

如何获取有关D的信息?

2 个答案:

答案 0 :(得分:3)

C是对象的集合,您需要再次循环才能访问C。

Also In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct. There can be two types of constructors in C#.

List<A> listA = new List<A>;
    if (listA != null)
    {
          foreach (var temp in listA)
          {
             foreach(var d in temp.C) 
             {
                 //ToDo Interact with d.D
             }
          }
    }

答案 1 :(得分:0)

PWT的答案很好,但是如果您确实想做一行if语句,则可以使用System.Linq来完成。这样得出的结果与您在问题中试图达到的结果相同。

List<A> listA = new List<A>();
if (listA != null)
{
    foreach (var temp in listA)
    {
        if (temp.C.Any(c => c.D == 123))
        {
            // todo your logic
        }
    }
}