ScG
ScG

Reputation: 1073

Loop through 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 have populated an object of class A called obj. How can I loop through this object and print values. Do I have to use two foreach's like the one show here or is there a better way?

 foreach (var z  in obj)
            {
                // print z.something;
                foreach (var x in z.b)
                {
                    // print x.elseelse;
                }
            }

Upvotes: 3

Views: 483

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062915

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 project the string:

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

Upvotes: 2

Guffa
Guffa

Reputation: 700372

As there is only one collection, you don't need two loops. As your obj variable is not a collection, you can't even make a loop over it.

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

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

Upvotes: 2

wRAR
wRAR

Reputation: 25693

No, just one foreach through obj.b:

foreach (var z in obj.b)
{
}

Upvotes: 1

Michael Haren
Michael Haren

Reputation: 108286

Your question is a little unclear to me. I'm assuming you have a collection of some object A and A has a collection property. If that's the case:

Your solution is the most straightforward way so I'd go with that.

You could use linq, but it won't really make this any faster or clearer. Something akin to this with SelectMany, which flattens many IEnumerables into one:

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

Upvotes: 2

Related Questions