anmarti
anmarti

Reputation: 5143

How to get an element range in linq within a sequence?

I have this query to collection:

Panel thePanel = menuCell.Controls.OfType<Panel>()
                    .Where(panel => panel.Controls.OfType<HyperLink>().Any(
                        label => label.ID == clas))
                    .FirstOrDefault();

This gets only the Panel that has an hyperlink with a certain id. I need to get not only the firstOrDefault but the matched element (only the first) and the 2 next within the sequence. I didn't try anything because don't know how.

Upvotes: 5

Views: 437

Answers (2)

SWeko
SWeko

Reputation: 30932

If you want to find one panel with the specified condition, and then take it, and the two next, regardless of whether they satisfy the condition or not, you could do:

IEnumerable<Panel> thePanelAndTwoNext = menuCell.Controls.OfType<Panel>()
                .SkipWhile(panel => !panel.Controls.OfType<HyperLink>()
                                       .Any(label => label.ID == clas))
                .Take(3);

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

This will return first three panels, which have hyperlinks with a certain id

var thePanels = menuCell.Controls.OfType<Panel>()
                    .Where(panel => panel.Controls.OfType<HyperLink>()
                                         .Any(label => label.ID == clas))
                    .Take(3);

If you need first panel which have hyperlinks with a certain id, and next two panels whatever they have:

var thePanels = menuCell.Controls.OfType<Panel>()
                        .SkipWhile(panel => !panel.Controls.OfType<HyperLink>()
                                                 .Any(label => label.ID == clas))
                        .Take(3);

Upvotes: 7

Related Questions