Implement the Where ...
Implement the Where ...
Here's how you can implement the Where
method in C#, along with an explanation:
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
foreach (TSource element in source)
{
if (predicate(element))
{
yield return element;
}
}
}
Explanation:
The Where
method is an extension method that operates on an IEnumerable<TSource>
collection. It takes two parameters:
source
: The collection of elements to filter.predicate
: A delegate of type Func<TSource, bool>
that represents the condition to filter the elements.The method uses a foreach
loop to iterate through each element in the source
collection.
For each element, the predicate
delegate is invoked with the current element as an argument. The predicate
returns a boolean value indicating whether the element satisfies the specified condition.
If the predicate
returns true
for the current element, it is yielded using the yield return
statement. This allows the method to return the filtered elements one at a time, without creating a new collection upfront.
The `yield...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào