简体   繁体   中英

Accessing List Constructor

First of all apologize if the terminology is not right. I have a constructor like this below:

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

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

I'm trying to access information on D like this:

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

How do I get information on D?

C is a collection of objects, you need to loop again to access 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
             }
          }
    }

PWT's answer is great, but if you did want to do a one line if statement, you could do this, using System.Linq. This gives the same result as you were trying to achieve in your question.

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM