这些是我的对象类型:
public class Room
{
public Giver Giver
{
get;
set;
}
[XmlElement("Receiver")]
public List<Receiver> Receiver
{
get;
set;
}
}
public class Receiver
{
[XmlAttribute("type")]
public string Type
{
get; set;
}
[XmlAttribute("Id")]
public String Id
{
get; set;
}
}
class Program
{
static void Main(string[] args)
{
List<Room> list = new List<Room>
{
new Room
{
Giver = new Giver{ Type="Generous", PID="something"},
Receiver = new List<Receiver>{new Receiver{Type="test1", Id="test2"},
new Receiver{Type="test3", Id="test4"},
new Receiver{Type="test5", Id="test6"}},
}
};
}
}
如果我声明列出eroom ,我如何遍历eroom列表,其中声明了Receiver列表并访问Receiver的属性?
例如,我有:
List<Room> eroom;
for (int i = 0; i < eroom.Count; i++)
{
Console.WriteLine("Giver Type: " + eroom[i].Giver.Type);
Console.WriteLine("Giver PID: " + eroom[i].Giver.PID);
//code below returns error
Console.WriteLine("Receiver Id: " + eroom[i].Receiver.Id);
}
如何在for循环中访问Receiver的ID?
答案 0 :(得分:0)
List<Room> eroom;
eroom.ForEach((room) =>{
Console.WriteLine("Giver Type: " + room.Giver.Type);
Console.WriteLine("Giver FNm: " + room.Giver.PID);
room.Receiver.ForEach((receiver) =>{
Console.WriteLine(receiver.Id);
});
});
答案 1 :(得分:0)
你需要在eroom
内部进行第二次循环。由于Receiver
(变量,而不是类)是一个列表,因此每个ID都有多个ID。
你需要这样的东西:
foreach (Receiver r in eroom[i].Receiver)
Console.WriteLine("Receiver Id: " + r.Id;
你也可以使用普通的for循环,使用0和eroom [i] .Reciever.Count作为界限。