Câu hỏi phỏng vấn C#
Câu hỏi

Implement the Where ...

Câu trả lời

Here's how you can implement the Where method in C#, along with an explanation:

csharp Copy
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:

  1. 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.
  2. The method uses a foreach loop to iterate through each element in the source collection.

  3. 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.

  4. 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.

  5. The `yield...

expert

expert

Gợi ý câu hỏi phỏng vấn

senior

What interface should your data structure implement to make the Where method work?

entry

What is C#?

senior

Explain the difference between Select and Where

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào