我有两节课 class A{ public string something { get; set; } public IListB b= new ListB();}class B{ public string else { get; set; } public string elseelse { get; set; }} 我已经填充了一个名为obj的A类对象.如何遍历此对象并
class A { public string something { get; set; } public IList<B> b= new List<B>(); } class B { public string else { get; set; } public string elseelse { get; set; } }
我已经填充了一个名为obj的A类对象.如何遍历此对象并打印值.我是否必须使用两个foreach,就像这里的一个节目,还是有更好的方法?
foreach (var z in obj) { // print z.something; foreach (var x in z.b) { // print x.elseelse; } }
var qry = from z in obj from x in z.b select new { z, x }; foreach (var pair in qry) { Console.WriteLine("{0}, {1}", pair.z.something, pair.x.elseelse); }
要么
var qry = from z in obj from x in z.b select new { z.zomething, x.elseelse }; foreach (var item in qry) { Console.WriteLine("{0}, {1}", item.something, item.elseelse); }
或投射字符串:
var qry = from z in obj from x in z.b select z.zomething + ", " + x.elseelse; foreach (string s in qry) { Console.WriteLine(s); }