Search code examples
c#linqlinq-query-syntax

LINQ query syntax with multiple statements


Can this method be rewritten using LINQ's query syntax?

public IEnumerable<Item> GetAllItems()
{
    return Tabs.SelectMany(tab =>
        {
            tab.Pick();
            return tab.Items;
        });
}

I cannot figure out where to place tab.Pick() method call.


Solution

  • No, query expressions in LINQ require each selection part etc to be a single expression, not multiple statements.

    However, you could write a separate method:

    public IEnumerable<Item> PickItems(Tab tab)
    {
        tab.Pick();
        return tab.Items;
    }
    

    Then use:

    var query = from tab in tabs
                from item in PickItems(tab)
                select item.Name;
    

    (Or whatever you want to do.)