Linq Get all items between 2 matching elements

Provided a list, I want to select all items between the 2 given. (including the begin and end params)

My current solution is as follows:

private IEnumerable<string> GetAllBetween(IEnumerable<string> list, string begin, string end)
{
    bool isBetween = false;
    foreach (string item in list)
    {
        if (item == begin)
        {
            isBetween = true;
        }
        if (item == end)
        {
            yield return item;
            yield break;
        }
        if (isBetween)
        {
            yield return item;
        }
    }
}

But surely there must be a pretty linq query that accomplishes the same thing?

Jon Skeet
people
quotationmark

You can nearly use SkipWhile and TakeWhile, but you want the last item as well - you want the functionality of TakeUntil from MoreLINQ. You can then use:

var query = source.SkipWhile(x => x != begin)
                  .TakeUntil(x => x == end);

people

See more on this question at Stackoverflow