LINQ : Where Query Operator

Imagine that you need to list the names and cities of customers from Italy. To filter a set of items, you can use the Where operator, which is also called a restriction operator because it restricts a set of items.

var expr =
from c in customers
where c.Country == Countries.Italy
select new { c.Name, c.City };
Here are the signatures of the Where operator:
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, int, bool> predicate);

As you can see, two signatures are available.we used the first signature, which enumerates items of the source sequence and yields those that verify the predicate
(c.Country == Countries.Italy). The second signature accepts an additional parameter of type Integer for the predicate. This argument is used as a zero-based index of the elements within the source sequence. Keep in mind that if you pass null arguments to the predicates, an ArgumentNullException error will be thrown. You can use the index parameter to start filtering by a particular index

var expr =
customers
.Where((c, index) => (c.Country == Countries.Italy && index >= 1))
.Select(c => c.Name);

we cannot use the LINQ query syntax because the Where version that we want to call is not supported by an equivalent LINQ query clause. We will use both
syntaxes from here onward.


No comments:

Post a Comment