spwert
spwert

Reputation: 98

Should I replace these nested foreach loops with LINQ, and how?

I receive data from a service in the following format:

public class Foo
{
    string Name;
}
public class Bar
{
    int ID;
    List<Foo> Foos;
}
public class Container
{
    List<Bar> Bars;
}

I need to write a method that returns the Names of all of the Foos in a Container, paired with the ID of their associated Bar, in the following class:

public class FooBar
{
    int BarID;
    Foo Name;
}

This is what I came up with:

IEnumerable<FooBar> FooBars(Container c)
{
    foreach (var b in c.Bars)
    {
        foreach (var f in b.Foos)
        {
            yield return new FooBar() { BarID = b.ID; Name = f.Name; }
        }
    }
}

I have two questions:

Upvotes: 1

Views: 392

Answers (1)

Jonathon Chase
Jonathon Chase

Reputation: 9704

This is the query syntax for LINQ's SelectMany, which allows you to do what you're describing. As far as why you would do this, I personally find it more easily readable.

from b in c.Bars
from f in b.Foos
select new FooBar {BarID = b.ID, Name = f.Name};

Upvotes: 5

Related Questions