Scrolling Collections

I have two classes

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

I populated an object of class A called obj. How can I scroll this object and print the values. Should I use two foreach, for example, one show or is there a better way?

 foreach (var z  in obj)
            {
                // print z.something;
                foreach (var x in z.b)
                {
                    // print x.elseelse;
                }
            }
+3
source share
4 answers
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);
}

or

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

or program the line:

var qry = from z in obj
          from x in z.b
          select z.zomething + ", " + x.elseelse;
foreach (string s in qry)
{
     Console.WriteLine(s);
}
+2
source

Your question is a little unclear to me. I assume that you have a collection of some objects A and A has a collection property. If this is the case:

Your solution is the easiest way, so I would go with that.

You can use linq, but it really won't make it faster or clearer. Something similar to this with SelectManywhich smooths many IEnumerables in one:

foreach(var x in obj.SelectMany(z=>z.b)) { }
+2

, . obj , .

Just display the properties in your object and go through the collection:

// print obj.something; 
foreach (var x in obj.b) {
  // print x.else; 
  // print x.elseelse; 
} 
+2
source

No, only one foreach via obj.b:

foreach (var z in obj.b)
{
}
+1
source

Source: https://habr.com/ru/post/1739842/


All Articles