Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

linq

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.

like image 631
anmarti Avatar asked Dec 28 '12 12:12

anmarti


People also ask

What is the use of range in LINQ?

LINQ Range Method. In LINQ, Range method or operator is used to generate sequence of integers or numbers based on specified values of start index and end index. Following is the syntax of LINQ Range method to generate sequence of numbers based on specified index values.

How to generate a sequence of integral numbers within a range?

Linq Range Method in C#: This method is used to Generates a sequence of integral (integer) numbers within a specified range. The following is the signature of this method. This method has 2 integer parameters.

How do you use LINQ in a list?

In the listing, the LINQ statement queries the dynamic range of integers from 33 to 42 and uses the projection syntax to create a new type that is an object containing the number and the word Even or Odd indicating the word’s parity (or evenness or oddness).

How do you return even numbers in a LINQ query?

Listing 1: A basic query that returns even numbers. The LINQ query is the statement that begins with Dim evens = From num In numbers. The first word after the From keyword is referred to as the range variable. The Range variable plays the same role as the iteration variable in a for loop.


1 Answers

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);
like image 87
Sergey Berezovskiy Avatar answered Sep 29 '22 16:09

Sergey Berezovskiy