[英]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: 我正在尝试像这样访问有关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
{
}
}
}
How do I get information on D? 我如何获得有关D的信息?
C is a collection of objects, you need to loop again to access C. C是对象的集合,您需要再次循环才能访问C。
Also In C#, constructor is a special method which is invoked automatically at the time of object creation. 同样在C#中,构造函数是一种特殊的方法,在创建对象时会自动调用它。 It is used to initialize the data members of new object generally.
通常用于初始化新对象的数据成员。 The constructor in C# has the same name as class or struct.
C#中的构造函数与类或结构具有相同的名称。 There can be two types of constructors in C#.
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. PWT的答案很好,但是如果您确实想做一行
if
语句,则可以使用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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.